OC之日期与时间类NSDate

//OC为处理日期、时间提供了NSDate对象,还提供了日期格式器来处理日期与字符串之间的转换

//获取当前日期、时间的对象
NSDate *currentDate = [NSDate date];
//获取的时间默认是0时区的时间,转换成北京时间要+8小时
NSLog(@"currentDate = %@",currentDate);//

//获取从当前时间开始,1天之后的日期
NSDate * onedayLater = [NSDate dateWithTimeIntervalSinceNow:60 * 60 * 24];
NSLog(@"onedayLater = %@",onedayLater);
//获取当前时间开始,1天之前的日期
NSDate * oneDayBefore = [NSDate dateWithTimeIntervalSinceNow:- 60 * 60 * 24];
NSLog(@"oneDayBefore = %@",oneDayBefore);

//获取从1970年1月1日开始,30年之后的日期
NSDate * date1 = [NSDate dateWithTimeIntervalSince1970:(30*365+7) * 60*60*24];
NSLog(@"date1 = %@",date1);

//获取系统当前的NSLocale,NSLocale 代表一个语言,国际环境,比如大陆的简体中文,就可通过NSLocale 对象来代表,同样一个日期,在不同的语言、国际环境下,显示出来的字符串是不同的。
NSLocale * locale = [NSLocale currentLocale];
//获取NSDate在当前语言环境下对应的字符串
NSString *str = [currentDate descriptionWithLocale:locale];//
NSLog(@"currentdate = %@",str);

//获取两个日期之间较早的日期
NSDate * earlierDate = [oneDayBefore earlierDate:onedayLater];
NSLog(@"earlierDate = %@",earlierDate);
//获取两个日期之间较晚的日期
NSDate * latterDate = [onedayLater earlierDate:onedayLater];
NSLog(@"latterDate = %@",latterDate);

//比较两个日期,,compare:方法返回NSComparisonResult枚举值,该枚举类型包含NSOrderedAscending、NSOrderedSame 和NSOrderedDescending三个值(值为-1,0,1),分别代表调用compare:方法的日期与被比较的日期是升序、相同、降序排列
NSInteger res = [latterDate compare:earlierDate];
if (res > 0) {
    
}else {
    NSLog(@"latterDate 不比 earlierDate 晚");
}
//获取两个时间之间的差
NSTimeInterval timeInterval = [latterDate timeIntervalSinceDate:earlierDate];
NSLog(@"latterDate 与 earlierDate 之间相差%.3lf",timeInterval);
//获取指定时间与当前时间的差
timeInterval = [latterDate timeIntervalSinceNow];
NSLog(@"指定时间与当前时间相差%.3lf",timeInterval);

打印结果
~~~
2016-06-09 21:50:18.865 时间相关[1370:54710] currentDate = 2016-06-09 13:50:18 +0000
2016-06-09 21:50:18.866 时间相关[1370:54710] onedayLater = 2016-06-10 13:50:18 +0000
2016-06-09 21:50:18.866 时间相关[1370:54710] oneDayBefore = 2016-06-08 13:50:18 +0000
2016-06-09 21:50:18.866 时间相关[1370:54710] date1 = 2000-01-01 00:00:00 +0000
2016-06-09 21:50:18.867 时间相关[1370:54710] currentdate = Thursday, June 9, 2016 at 9:50:18 PM China Standard Time
2016-06-09 21:50:18.867 时间相关[1370:54710] earlierDate = 2016-06-08 13:50:18 +0000
2016-06-09 21:50:18.869 时间相关[1370:54710] latterDate = 2016-06-10 13:50:18 +0000
2016-06-09 21:50:18.870 时间相关[1370:54710] latterDate 与 earlierDate 之间相差172800.000
2016-06-09 21:50:18.871 时间相关[1370:54710] 指定时间与当前时间相差86400


------------------------------------
喜欢的话,帮忙点一下喜欢,谢谢!
如果有错误之处或者偏差,还请斧正!
欢迎大家留言提问,技术要交流才能更快成长!
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容