IOS NSDate时间戳字符串转换

首先我们大致理解一下 IOS中时间戳相关的概念:

NSDate这块可以分为四个部分去理解:时间戳NSTimeInterval,字符串NSString,Date格式。格式转换器NSDateFormatter。

1. 获取当前时间Date:

NSDate *date = [NSDate date];

2.获取当前时间时间戳:

NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970];

3.字符串格式的时间转换:

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

[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSString *timeStr = [formatter stringFromDate:date];

注意:时间戳转换的格式要区分好大小写。不要大量创建NSDateFormatter,对性能消耗比较大。

 

类型转换:

1.NSDate转NSString(需要formatter)

NSString *timeStr = [formatter stringFromDate:date];

2.NSSting转时间NSDate(需要formatter)

NSDate *endDate = [formatter dateFromString:@"2017-07-24 23:59:59"];

3.NSDate转时间戳

NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970];//当前时间距离1970年多久

NSTimeInterval timeInterva = [date timeIntervalSinceDate:startDate];//date距离StratDate多久

NSTimeInterval timeInterva = [date timeIntervalSinceNow];//date距离当前时间多久

4.时间戳转NSDate

NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:dateStamp];

5.String无法直接转时间戳

6.时间戳转NSString(系统格式时间)

NSString *timeStr = [NSString stringWithFormat:@"%.0f", [startDate timeIntervalSince1970]];


时间转换中格式的含义:

d:1~31 (月份的第几天, 带0)

D:1~366 (年份的第几天,带0)

h:1~12 (0 padded Hour (12hr)) 带0的时, 12小时制

H:0~23 (0 padded Hour (24hr))  带0的时, 24小时制

m:0~59 (0 padded Minute) 分钟

M/MM:1~12 (0 padded Month) 第几月

y/yyyy:(Full Year) 完整的年份

Y/YYYY:以周为计算单位计算年,会出现问题是:这周跨年,那么年份则直接是下一年。通常用不到

s:0~59 (0 padded Second) 秒数


关于时间格式更多详情的问题,可以参考这篇文章:

http://blog.csdn.net/ouyangtianhan/article/details/45921389

你可能感兴趣的:(IOS NSDate时间戳字符串转换)