iOS 时间戳 时间串 比较和转换

1.时间转字符串

NSDate * date = [NSDate date];
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd hh:mm"];
    NSString * dateStr = [formatter stringFromDate:date];
    NSLog(@"%@",dateStr);

2016-06-29 02:30


2.字符串转时间

NSString * dateStr = @"2016-06-30 12:00:00 0";
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss z"];
    NSDate * date = [formatter dateFromString:dateStr];
    NSLog(@"%@",date);

3.时间戳转时间串

    CGFloat time = [startTime doubleValue]/1000;
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy.MM.dd"];
    NSString * str1 = [dateFormatter stringFromDate: detaildate];


4.时间戳与当前时间对比,做倒计时
 CGFloat time1 = [_order.gmt_expire doubleValue]/1000;
        NSDate *date1=[NSDate dateWithTimeIntervalSince1970:time1];
        
        NSTimeInterval time2 =[date1 timeIntervalSinceNow];
        int min=((int)time2)/60;
        cell.warnLabel.text =[NSString stringWithFormat:@"请您于%ld分钟内完成支付,否则订单将被取消",(long)min];


5.时间转时间戳

 NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[date timeIntervalSince1970]*1000; // *1000 是精确到毫秒,不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a]; //转为字符型
    NSLog(@"%@",timeString);






你可能感兴趣的:(iOS 时间戳 时间串 比较和转换)