iOS开发之纯代码约束

我们在平时开发中, 大多数的控件都需要进行约束, 约束的方法比较多, 例如autolayout等. 今天我们就来谈谈如何进行纯代码约束.

首先我们来说*种情况, 假如我们有一个label叫namelabel, 现在我们需要让namelabel距离self.view的上边距100, 距离左边距20.那么我们用纯代码需要这样写.

// 左
NSLayoutConstraint * nameLabelLeading = [NSLayoutConstraint constraintWithItem:nameLabel attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:20.f];
// 上
NSLayoutConstraint * nameLabelTop = [NSLayoutConstraint constraintWithItem:nameLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:0.1f constant:100.f];
[self.view addConstraints:@[nameLabelLeading,nameLabelTop]];

这样就加上了namelabel的约束, 这三句代码就可以让namelabel距离左边距20 距离上边距100.

还有一种是需要给namelabel一个宽度和高度, 假如和self.view同高同宽.

// 宽
NSLayoutConstraint * nameLabelWidth = [NSLayoutConstraint constraintWithItem:nameLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:self.view.bounds.size.width];
// 高
NSLayoutConstraint * nameLabelHeigth = [NSLayoutConstraint constraintWithItem:nameLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:self.view.bounds.size.height];

[self.view addConstraints:@[nameLabelHeigth,nameLabelWidth]];

这三句代码就可以给namelabel一个宽度和高度, 分别是和self.view的宽度和高度相等.
这样就完成了基本的纯代码约束, 是不是很简单呢.

iOS-使用代码约束布局(Masonry)

一、引子

学完了可视化编程的Xib和Storyboard,LZ对它们的感受就是的就是UI控件创建直接拖拽,尺寸适配加约束,Storyboard的页面跳转逻辑清晰可见,比起代码布局节省了很多的工作量。但是LZ相信还是很多人喜欢用纯代码来编写一个程序的(LZ就是一个,用代码写出来东西的成就感很足!),所以今天在这里给喜爱纯代码编程的程序猿们介绍一下纯代码约束布局的工具——Masonry。

二、Masonry介绍

Masonry源码下载地址:https://github.com/SoleMY/Masonry

Masonry是一个轻量级的布局框架 拥有自己的描述语法 采用更优雅的链式语法封装自动布局 简洁明了 并具有高可读性 而且同时支持 iOS 和 Max OS X。

Masonry支持的属性:

/// 左侧
@property (nonatomic, strong, readonly) MASConstraint *left;
/// 上侧
@property (nonatomic, strong, readonly) MASConstraint *top;
/// 右侧
@property (nonatomic, strong, readonly) MASConstraint *right;
/// 下侧
@property (nonatomic, strong, readonly) MASConstraint *bottom;
/// 首部
@property (nonatomic, strong, readonly) MASConstraint *leading;
/// 底部
@property (nonatomic, strong, readonly) MASConstraint *trailing;
/// 宽
@property (nonatomic, strong, readonly) MASConstraint *width;
/// 高
@property (nonatomic, strong, readonly) MASConstraint *height;
/// 横向中点
@property (nonatomic, strong, readonly) MASConstraint *centerX;
/// 纵向中点
@property (nonatomic, strong, readonly) MASConstraint *centerY;
/// 文本基线
@property (nonatomic, strong, readonly) MASConstraint *baseline;

// 在Masonry的源码中我们可以看到他们对应的NSLayoutAttribute的属性对应如下
- (MASConstraint *)left {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft];
}

- (MASConstraint *)top {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTop];
}

- (MASConstraint *)right {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRight];
}

- (MASConstraint *)bottom {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottom];
}

- (MASConstraint *)leading {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeading];
}

- (MASConstraint *)trailing {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailing];
}

- (MASConstraint *)width {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeWidth];
}

- (MASConstraint *)height {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeHeight];
}

- (MASConstraint *)centerX {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterX];
}

- (MASConstraint *)centerY {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterY];
}

- (MASConstraint *)baseline {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBaseline];
}

iOS8之后Masonry新出了几个属性:

/// 距离边框的距离,等同于选中Storyboard的Constrain to margins后加约束
@property (nonatomic, strong, readonly) MASConstraint *leftMargin;
@property (nonatomic, strong, readonly) MASConstraint *rightMargin;
@property (nonatomic, strong, readonly) MASConstraint *topMargin;
@property (nonatomic, strong, readonly) MASConstraint *bottomMargin;
@property (nonatomic, strong, readonly) MASConstraint *leadingMargin;
@property (nonatomic, strong, readonly) MASConstraint *trailingMargin;
@property (nonatomic, strong, readonly) MASConstraint *centerXWithinMargins;
@property (nonatomic, strong, readonly) MASConstraint *centerYWithinMargins;

- (MASConstraint *)leftMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeftMargin];
}

- (MASConstraint *)rightMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRightMargin];
}

- (MASConstraint *)topMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTopMargin];
}

- (MASConstraint *)bottomMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottomMargin];
}

- (MASConstraint *)leadingMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeadingMargin];
}

- (MASConstraint *)trailingMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailingMargin];
}

- (MASConstraint *)centerXWithinMargins {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterXWithinMargins];
}

三、代码示例

#import "RootViewController.h"
// 引入头文件
#import "Masonry.h"
@interface RootViewController ()

@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
#pragma mark label
    
    // 添加约束,不需要设置frame
    UILabel *label = [UILabel new];
    label.backgroundColor = [UIColor redColor];
    // 添加父视图,视图添加完成后才能进行布局
    [self.view addSubview:label];
    
    // 布局实现label方法
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        // 距离上边50
        // make:相当于你要布局的视图
        // equalTo(参照视图对象),如果参照视图是self.view,可以不设置参照视图的属性
        // offset(距离数值)
        make.top.equalTo(self.view).offset(50);
        
        // 距离左边100
        make.left.equalTo(self.view).offset(100);
        
        // 距离右边100
        make.right.equalTo(self.view).offset(-100);
        
        // 距离下边500
        make.bottom.equalTo(self.view).offset(-500);
        
    }];
#pragma mark label1
    UILabel *label1 = [UILabel new];
    label1.backgroundColor = [UIColor greenColor];
    [self.view addSubview:label1];
    
    // 布局实现label1方法
    // 先布局参照视图,否则约束容易丢失
    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
        // equalTo(自定义视图),需要设置视图的属性
        // 如果数值为0,可以不写offset()
        make.top.equalTo(label.mas_bottom).offset(50);
        make.leading.equalTo(label.mas_leading);
        make.trailing.equalTo(label.mas_trailing);
        // 高度60
        // mas_equalTo(数值)
        make.height.mas_equalTo(60);
        
    }];
    
#pragma mark label2
    UILabel *label2 = [UILabel new];
    label2.backgroundColor = [UIColor grayColor];
    [self.view addSubview:label2];
    
    // 设置距离参照视图的内边距 (上左下右)
    UIEdgeInsets padding = UIEdgeInsetsMake(400, 100, 100, 100);
    
    // 布局实现label2方法
    // 先布局参照视图,否则约束容易丢失
    [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
        // 设置约束视图的边界距离self.view的边界值
        make.edges.equalTo(self.view).insets(padding);
        
//        make.top.equalTo(self.view).offset(400);
//        make.left.equalTo(self.view).offset(100);
//        make.right.equalTo(self.view).offset(-100);
//        
//        make.bottom.equalTo(self.view).offset(-100);
        
    }];
#pragma mark label3
    UILabel *label3 = [UILabel new];
    label3.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:label3];
    
    [label3 mas_makeConstraints:^(MASConstraintMaker *make) {
        // 设置中心点一致
        make.center.equalTo(label2);
        
        // 设置大小
        // make.width = label2.width - 40
        // make.heigth = label2.height - 60
        make.size.equalTo(label2).sizeOffset(CGSizeMake(-40, -60));
    }];

    
}

@end

iOS-WKWebView取消自动选中灰色背景

在IOS中WKWebView有些地方tap点击会有一个灰色背景图层出现,会让用户感觉是个bug.

%title插图%num
-webkit-tap-highlight-color这个属性只用于iOS (iPhone和iPad)。当你点击一个链接或者通过Javascript定义的可点击元素的时候,它就会出现一个半透明的灰色背景。要重设这个表现,你可以设置-webkit-tap-highlight-color为任何颜色。想要禁用这个高亮,设置颜色的alpha值为0即可。

示例:

//设置高亮色为50%透明的红色:
-webkit-tap-highlight-color: rgba(255,0,0,0.5);

//设置高亮色透明
-webkit-tap-highlight-color: rgba(0,0,0,0);

解决方案:

//swift代码
//去除wkwebview tap选中颜色
//script1 和script2都可以
func disable_webkit_tap_highlight_color() {
//let script1= “function addStyleString(str) {” + “var node = document.createElement(‘style’);” + “node.innerHTML = str;” + “document.body.appendChild(node);” + “}” + “addStyleString(‘* {-webkit-tap-highlight-color: rgba(0,0,0,0);}’);”
let script2= “document.body.style.webkitTapHighlightColor=’transparent’;”
self.webView.evaluateJavaScript(script2, completionHandler: nil)
}

 

iOS-EKEventEditViewController踩坑记录

一、EKEventEditViewController是什么?
EKEventEditViewController是添加日历事件的一个ViewController
通过设置event,然后push到这个VC 就展示出来这个事件的便捷页面。

%title插图%num

二、部分iOS系统上的问题

%title插图%num
stackoverflow上这个问题的解决方案

在iOS12.2.0–13.3beta版本中,这个问题一直存在,直到13.3beta苹果才修复了这个问题。

三、解决方案一,使用继承
stackoverflow上这个问题的解决方案

继承EKEventEditViewController这个类,在子类中进行修复。
原理就是在出现这个问题的iOS版本中,设置event的时候,先设置event.title = nil,将真正的title存放到变量中。
在viewWillAppear方法中把真正测title重新赋值给event.title ;
在viewDidAppear将键盘收起,这样就规避了苹果的这个bug。

四、解决方案二,使用分类
使用继承的方式解决这个问题会有个小问题,就是在点击取消按钮的时候,会发现actionsheet提示变成英文

%title插图%num

所以第二种解决方案是使用分类的方式,进行hook
在viewWillAppear方法中把真正测title重新赋值给event.title ;
在viewDidAppear将键盘收起。

iOS开发-Masonry约束宽高比

先看看Masonry的源代码,可以发现两个属性
这两个属性可以设置视图中的宽高比例
使用multipliedBy必须是对同一个控件本身,比如,上面的代码中,我们都是对bottomInnerView.mas_width本身的,如果修改成相对于其它控件,会出问题。

//multipler属性表示约束值为约束对象的乘因数
– (MASConstraint * (^)(CGFloat multiplier))multipliedBy;

//dividedBy属性表示约束值为约束对象的除因数,可用于设置view的宽高比
– (MASConstraint * (^)(CGFloat divider))dividedBy;

具体使用

// width/height比为1/3.0,要求是同一个控件的属性比例
[bottomInnerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.bottom.mas_equalTo(bottomView);
make.center.mas_equalTo(bottomView);
// 注意,这个multipliedBy的使用只能是设置同一个控件的,比如这里的bottomInnerView,
// 设置高/宽为3:1
make.height.mas_equalTo(bottomInnerView.mas_width).multipliedBy(3);

make.width.height.mas_equalTo(bottomView).priorityLow();
make.width.height.lessThanOrEqualTo(bottomView);
}];

 

 

前端开发:Mac安装NVM报错curl: (7) Failed to connect to raw.githubusercontent.com port 443: Connection refused

之前在Mac电脑上安装nvm的时候,遇到安装不成功报错,然后提示的报错信息是:

curl: (7) Failed to connect to raw.githubusercontent.com port 443: Connection refused

 

报错截图如下:

%title插图%num

经过分析之后得出结论,是因为GitHub的一些域名的DNS解析被污染造成的DNS解析过程无法通过域名获取正确的IP地址,也就造成在安装的时候失败,失败的原因是没有初始化引起的。

 

解决步骤如下所示:

1.打开链接 https://www.ipaddress.com/  然后在网页里面输入访问不了的域名,即raw.githubusercontent.com ;

 

2.查询一下域名raw.githubusercontent.com 对应的正确的IP地址;

 

3.然后在Mac电脑本机上面的host文件里替换系统的host文件,打开电脑Finder,然后使用快捷键组合:Shift + Command+g 前往文件夹,输入/etc/hosts  点击“前往”,

%title插图%num

直接进入系统hosts文件所在目录下,直接双击打开hosts文件;

%title插图%num

4. 在本机电脑打开的hosts文件里填写:

199.232.68.133 raw.githubusercontent.com

199.232.68.133 user-images.githubusercontent.com

199.232.68.133 avatars22.githubusercontent.com

199.232.68.133 avatars11.githubusercontent.com

%title插图%num

5.然后保存,就完美的解决了上述报错问题;

 

6.*后就可以成功安装nvm啦。

Android与IOS中获取时间戳的方法

什么是时间戳?

时间戳是自 1970 年 1 月 1 日(00:00:00 GMT)至当前时间的总秒数。它也被称为 Unix 时间戳(Unix Timestamp)。

iOS中获取毫秒时间戳获取方法:

UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;
  • 1

首先 [[NSDate date] timeIntervalSince1970] 是可以获取到后面的毫秒 微秒的 ,只是在保存的时候省略掉了, 如一个时间戳不省略的情况下为 1395399556.862046 ,省略掉后为一般所见 1395399556 。
所以想取得毫秒时用获取到的时间戳 * 1000 ,想取得微秒时 用取到的时间戳 * 1000 * 1000 。

NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];  
[formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss:SSS"];    
NSString *date =  [formatter stringFromDate:[NSDate date]];  
NSString *timeLocal = [[NSString alloc] initWithFormat:@"%@", date]; 
NSLog(@"%@", timeLocal);
  • 1
  • 2
  • 3
  • 4
  • 5

Android 中获取时间戳的方法

1.获取当前时间

import   java.text.SimpleDateFormat;      
  SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("yyyy年MM月dd日   HH:mm:ss");     
  Date curDate =  new Date(System.currentTimeMillis());  //毫秒级
//获取当前时间  
  String  str = formatter.format(curDate);  

 

 

2.获取系统时间

//取得系统时间  
//1。  
long time=System.currentTimeMillis();  

//2。  
final Calendar mCalendar=Calendar.getInstance();  
mCalendar.setTimeInMillis(time);  
取得小时:mHour=mCalendar.get(Calendar.HOUR);  
取得分钟:mMinuts=mCalendar.get(Calendar.MINUTE);  

//3。  
Time t=new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料  
t.setToNow(); // 取得系统时间。  
int year = t.year;  
int month = t.month;  
int date = t.monthDay;  
int hour = t.hour;    // 0-23  

//4。  
DateFormat df = new SimpleDateFormat("HH:mm:ss");  
df.format(new Date());  

 

 

3.时间工具类

import android.util.Log;        
import java.text.ParseException;        
import java.text.SimpleDateFormat;        
import java.util.Calendar;        
import java.util.Date;        


public class TimeUtils {        

    /**    
     * 获取当前时间    
     * @return    
     */        
    public static String getNowTime(){        
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");        
        Date date = new Date(System.currentTimeMillis());        
        return simpleDateFormat.format(date);        
    }        
    /**    
     * 获取时间戳    
     *    
     * @return 获取时间戳    
     */        
    public static String getTimeString() {        
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");        
        Calendar calendar = Calendar.getInstance();        
        return df.format(calendar.getTime());        
    }        
    /**    
     * 时间转换为时间戳    
     * @param time:需要转换的时间    
     * @return    
     */        
    public static String dateToStamp(String time)  {        
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        
        Date date = null;        
        try {        
            date = simpleDateFormat.parse(time);        
        } catch (ParseException e) {        
            e.printStackTrace();        
        }        
        long ts = date.getTime();        
        return String.valueOf(ts);        
    }        

    /**    
     * 时间戳转换为字符串    
     * @param time:时间戳    
     * @return    
     */        
    public static String times(String time) {    
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分");    
        @SuppressWarnings("unused")    
        long lcc = Long.valueOf(time);    
        int i = Integer.parseInt(time);    
        String times = sdr.format(new Date(i * 1000L));    
        return times;    

    }       
    /**    
     *获取距现在某一小时的时刻    
     * @param hour hour=-1为上一个小时,hour=1为下一个小时    
     * @return    
     */        
    public static String getLongTime(int hour){        
        Calendar c = Calendar.getInstance(); // 当时的日期和时间        
        int h; // 需要更改的小时        
        h = c.get(Calendar.HOUR_OF_DAY) - hour;        
        c.set(Calendar.HOUR_OF_DAY, h);        
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");        
        Log.v("time",df.format(c.getTime()));        
        return df.format(c.getTime());        
    }      
    /**   
     * 比较时间大小   
     * @param str1:要比较的时间   
     * @param str2:要比较的时间   
     * @return   
     */      
    public static boolean isDateOneBigger(String str1, String str2) {      
        boolean isBigger = false;      
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");      
        Date dt1 = null;      
        Date dt2 = null;      
        try {      
            dt1 = sdf.parse(str1);      
            dt2 = sdf.parse(str2);      
        } catch (ParseException e) {      
            e.printStackTrace();      
        }      
        if (dt1.getTime() > dt2.getTime()) {      
            isBigger = true;      
        } else if (dt1.getTime() < dt2.getTime()) {      
            isBigger = false;      
        }      
        return isBigger;      
    }      
}        
  /**  
  * 当地时间 ---> UTC时间  
  * @return  
  */    
 public static String Local2UTC(){    
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
     sdf.setTimeZone(TimeZone.getTimeZone("gmt"));    
     String gmtTime = sdf.format(new Date());    
     return gmtTime;    
 }    

  /**  
  * UTC时间 ---> 当地时间  
  * @param utcTime   UTC时间  
  * @return  
  */    
 public static String utc2Local(String utcTime) {    
     SimpleDateFormat utcFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//UTC时间格式    
     utcFormater.setTimeZone(TimeZone.getTimeZone("UTC"));    
     Date gpsUTCDate = null;    
     try {    
         gpsUTCDate = utcFormater.parse(utcTime);    
     } catch (ParseException e) {    
         e.printStackTrace();    
     }    
     SimpleDateFormat localFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//当地时间格式    
     localFormater.setTimeZone(TimeZone.getDefault());    
     String localTime = localFormater.format(gpsUTCDate.getTime());    
     return localTime;    
 }   

 

 

使用案例:

package com.example.time;  

import java.text.ParseException;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import java.util.TimeZone;  

import android.app.Activity;  
import android.os.Bundle;  

public class MainActivity extends Activity {  

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  

        new Thread(){  
            public void run() {  
                String time = Local2UTC("2018-03-19 19:41:44");  
                System.out.println("time"+time);  
            };  
        }.start();  
    }  
    /** 
     * 将本地时间转为UTC时间 
     * @param strDate:需要转化的date 
     * @return 
     */  
    public String Local2UTC(String strDate){    
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
         String gmtTime = "";  
         sdf.setTimeZone(TimeZone.getTimeZone("gmt"));    
         gmtTime = sdf.format(stringToDate(strDate, "yyyy-MM-dd HH:mm:ss"));  
         return gmtTime;    
     }    
    /** 
     * 将string类型转换为date类型 
     * @param strTime:要转换的string类型的时间,时间格式必须要与formatType的时间格式相同 
     * @param formatType:要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 
     * @return 
     */  
    private Date stringToDate(String strTime, String formatType){  
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);  
        Date date = null;  
        try {  
            date = (Date) formatter.parse(strTime);  
        } catch (ParseException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        return date;  
    }  

}  

 

 

Unity中获取时间戳的方法

 

  /// 获取当前时间戳
    /// </summary>
    /// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳.</param>
    /// <returns></returns>
    public static long GetTimeStamp(bool bflag = true)
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        long ret;
        if (bflag)
            ret = Convert.ToInt64(ts.TotalSeconds);
        else
            ret = Convert.ToInt64(ts.TotalMilliseconds);
        return ret;
    }


    static DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
    public static string NormalizeTimpstamp0(long timpStamp)
    {
        long unixTime = timpStamp * 10000000L;
        TimeSpan toNow = new TimeSpan(unixTime);
        DateTime dt = dtStart.Add(toNow);
        return dt.ToString("yyyy-MM-dd");
    }


    /// <summary>
    /// 时钟式倒计时
    /// </summary>
    /// <param name="second"></param>
    /// <returns></returns>
    public string GetSecondString(int second)
    {
        return string.Format("{0:D2}", second / 3600) + string.Format("{0:D2}", second % 3600 / 60) + ":" + string.Format("{0:D2}", second % 60);
    }


    /// 将Unix时间戳转换为DateTime类型时间
    /// </summary>
    /// <param name="d">double 型数字</param>
    /// <returns>DateTime</returns>
    public static System.DateTime ConvertIntDateTime(double d)
    {
        System.DateTime time = System.DateTime.MinValue;
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0));
        Debug.Log(startTime);
        time = startTime.AddSeconds(d);
        return time;
    }


    /// <summary>
    /// 将c# DateTime时间格式转换为Unix时间戳格式
    /// </summary>
    /// <param name="time">时间</param>
    /// <returns>double</returns>
    public static double ConvertDateTimeInt(System.DateTime time)
    {
        double intResult = 0;
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
        intResult = (time - startTime).TotalSeconds;
        return intResult;
    }


    /// <summary>
    /// 日期转换成unix时间戳
    /// </summary>
    /// <param name="dateTime"></param>
    /// <returns></returns>
    public static long DateTimeToUnixTimestamp(DateTime dateTime)
    {
        var start = new DateTime(1970, 1, 1, 0, 0, 0, dateTime.Kind);
        return Convert.ToInt64((dateTime - start).TotalSeconds);
    }


    /// <summary>
    /// unix时间戳转换成日期
    /// </summary>
    /// <param name="unixTimeStamp">时间戳(秒)</param>
    /// <returns></returns>
    public static DateTime UnixTimestampToDateTime(DateTime target, long timestamp)
    {
        DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, target.Kind);
        return start.AddSeconds(timestamp);
    }

iOS开发:获取当前时间、当前时间戳(秒/毫秒)的方法

虽然之前总结整理过一篇关于iOS开发过程中时间和时间戳的博文,但是不是太完善,那么本章博文就来把之前那篇文章没有总结到的内容整理出来,依然只分享给有需要的人。具体内容如下所示。

一、获取当前时间

+(NSString*)getCurrentTimes {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

// 设置想要的格式,hh与HH的区别:分别表示12小时制,24小时制

[formatter setDateFormat:@”YYYY-MM-dd HH:mm:ss”];

NSDate *dateNow = [NSDate date];

//把NSDate按formatter格式转成NSString

NSString *currentTime = [formatter stringFromDate:dateNow];

return currentTime;

}

二、获取当前时间的时间戳

获取当前时间的时间戳有两种方法,*种是以秒为单位的,另一种是以毫秒为单位的,一定要根据实际情况来使用处理。

1、获取当前时间戳有两种方法(以秒为单位)

+(NSString *)getNowTimeStamp {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;

[formatter setDateStyle:NSDateFormatterMediumStyle];

[formatter setTimeStyle:NSDateFormatterShortStyle];

[formatter setDateFormat:@”YYYY-MM-dd HH:mm:ss”]; // 设置想要的格式,hh与HH的区别:分别表示12小时制,24小时制

//设置时区,这一点对时间的处理很重要

NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@”Asia/Shanghai”];

[formatter setTimeZone:timeZone];

NSDate *dateNow = [NSDate date];

NSString *timeStamp = [NSString stringWithFormat:@”%ld”, (long)[dateNow timeIntervalSince1970]];

return timeStamp;

}

+(NSString *)getNowTimeStamp2 {
NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];

NSTimeInterval a=[dat timeIntervalSince1970];

NSString*timeString = [NSString stringWithFormat:@”%0.f”, a];//转为字符型

return timeString;

}

2、获取当前时间戳 (以毫秒为单位)

+(NSString *)getNowTimeTimestamp3{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;

[formatter setDateStyle:NSDateFormatterMediumStyle];

[formatter setTimeStyle:NSDateFormatterShortStyle];

[formatter setDateFormat:@”YYYY-MM-dd HH:mm:ss SSS”]; // 设置想要的格式,hh与HH的区别:分别表示12小时制,24小时制

//设置时区,这一点对时间的处理有时很重要

NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@”Asia/Shanghai”];

[formatter setTimeZone:timeZone];

NSDate *datenow = [NSDate date];

NSString *timeSp = [NSString stringWithFormat:@”%ld”, (long)[datenow timeIntervalSince1970]*1000];

return timeSp;

}

代码实例如下:

%title插图%num

另附获取当前时间的方法步骤,仅供参考,具体如下图所示:

%title插图%num