1.NSDate
NSDate *date = [NSDate date];
NSLog(@"%@", date);//0时区, 格林尼治时间
//昨天的现在时刻
NSLog(@"%@", [NSDate dateWithTimeIntervalSinceNow:-24 * 60 * 60]);
//明天的现在时刻
NSLog(@"明年的现在时刻:%@", [NSDate dateWithTimeIntervalSinceNow:366 * 24 * 3600]);
2.NSTimeInterval(时间间隔)
//昨天的现在时刻与明年的现在时刻间隔多少秒
NSTimeInterval intervals = [[NSDate dateWithTimeIntervalSinceNow:-24 * 60 * 60] timeIntervalSinceDate:[NSDate dateWithTimeIntervalSinceNow:366 * 24 * 3600]];
NSLog(@"%lf", intervals);
时间戳是指: 某一时刻与1970年1月1日的时间间隔
NSDate *date = [NSDate date];
//客户端 向服务器端 传递时间戳(NSDate -> NSTimeInterval)
//现在时刻 与 1970年1月1日 的间隔
NSTimeInterval intervals1 = [date timeIntervalSince1970];
NSLog(@"%.2lf", intervals1);
//客户端 收到 服务端 传过来的时间戳, 把时间戳转化成时刻(NSTimeInterval -> NSDate)
//知道时间戳, 求时刻
NSDate *date4 =[NSDate dateWithTimeIntervalSince1970:360];
NSLog(@"%@", date4);
输出结果:
2015-08-22 20:53:16.180 NSDate[4360:434237] 1440247996.17
2015-08-22 20:53:16.180 NSDate[4360:434237] 1970-01-01 00:06:00 +0000
把这些搞懂能解决很多关于时间方面的问题:
来个例题
题: 计算当前时间和一个固定时间的差值,如果差值在60秒内,输出“刚 刚”,如果在60秒外3600秒内,输出“xx分钟前”,如果3600秒外, 3600*24秒内,输出“xx⼩小时前”
NSDate *date4 =[NSDate dateWithTimeIntervalSince1970:360];
NSTimeInterval intervals1 = [date timeIntervalSince1970];
NSDate *date5 = [NSDate dateWithTimeIntervalSinceNow:-20000];
NSTimeInterval intervals2 = [date5 timeIntervalSince1970];
NSTimeInterval temp = intervals1 - intervals2;
if (temp <= 60) {
NSLog(@"刚刚!");
} else if (temp <= 3600) {
NSLog(@"%.lf分钟前", temp / 60);
} else if (temp <= 3600 * 24) {
NSLog(@"%.lf小时前", temp / (3600 * 24));
} else {
NSLog(@"%@", date4);
}
NSDateFormatter, 日期格式类, 继承于NSFormatter, 把NSDate按照你给的格式转化成NSString
//NSDateFormatter, 日期格式类, 继承于NSFormatter, 把NSDate按照你给的格式, 转化成NSString
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy年MM月dd日 HH:mm:ss z";
//年: YYYY/yyyy, 大小写无影响, 四位年份 如:2015 yy/YY, 两位年份 如:15
//月: MM, 代表两位月份, 如07,11 M:一位月份,(只影响单月的, 并不影响两位数月份的输出)
//日: dd, 两位日期, 如02 26 d, 一位日期, 2 26
//DD, 这一天是这一年的第几天
//时: HH, 24小时制得 hh, 12小时制的
//分: mm, 分钟
//秒: ss, 秒
//z: 格式
//当前时刻 -> NSString
NSString *dateString = [formatter stringFromDate:date];
NSLog(@"%@", dateString);
//2014年05月01日 10点23分18秒
NSString *string = @"2014年05月01日 10点23分18秒";
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:@"YYYY年MM月dd日 HH点mm分ss秒"];
//NSTimeZone, 时区类
formatter1.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSDate *date6 = [formatter1 dateFromString:string];
NSLog(@"✨%@", date6);