iOS时间戳转换

获取当前时间

NSDate *startDate = [NSDate date]; // 获得时间对象

NSTimeZone *zone = [NSTimeZone systemTimeZone]; // 获得系统的时区

NSTimeInterval time = [zone secondsFromGMTForDate:startDate];// 以秒为单位返回当前时间与系统格林尼治时间的差

NSDate *dateNow = [startDate dateByAddingTimeInterval:time];// 然后把差的时间加上,就是当前系统准确的时间

时间戳转化为时间NSDate

- (NSString *)timeWithTimeIntervalString:(NSString *)timeString

{

NSDateFormatter *stampFormatter = [[NSDateFormatter alloc] init];

[stampFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

NSDate *stampDate2 = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]];// 服务器返回的10位时间戳不用除以1000

NSDate *stampDate2 = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]/1000.0];//服务器返回的13位时间戳要除以1000

NSString *dateString = [stampFormatter stringFromDate:stampDate2];

NSLog(@"时间戳转化时间 >>> %@",dateString);

return dateString;

}

时间转化为时间戳

// 当前时间

NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];

NSTimeInterval a=[date timeIntervalSince1970]*1000; // *1000 是精确到毫秒,不乘就是精确到秒

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

通过比较时间与当前时间返回年月日的方法

- (void)getBabyDetailAge:(NSString *)date

{

// 获得日期对象

NSDateFormatter *formatter_ = [[NSDateFormatter alloc] init];

formatter_.dateFormat = @"yyyy-MM-dd HH:mm:ss";

NSDate *createDate = [formatter_ dateFromString:date];

NSCalendar *gregorian = [[ NSCalendar alloc ] initWithCalendarIdentifier : NSCalendarIdentifierGregorian];

NSUInteger unitFlags = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear;

NSDateComponents *components = [gregorian components:unitFlags fromDate:createDate toDate:[NSDate date] options: 0 ];

NSInteger years = [components year];

NSInteger months = [components month ];

NSInteger days = [components day ];

}

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