本文将带你了解IOS开发入门ios 两个时间之间的比较,相差多少天多少小时多少分多少秒,希望本文对大家学IOS有所帮助。
两个时间之间的比较,相差多少天多少小时多少分多少秒
//
1. 今年// 1分钟内:刚刚// 1分~59分内:xx小时前// 昨天 xx:xx// xx-xx xx:xx // 2. 非今年//
xxxx-xx-xx xx:xx // Wed Jul 08 10:01:03 +0800 2015NSDateFormatter *fmt =
[[NSDateFormatter alloc] init];// 如果是真机调试,转换这种欧美时间,需要设置localefmt.locale =
[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];fmt.dateFormat
= @"EEE MMM dd HH:mm:ss Z yyyy";NSDate *createDate = [fmt dateFromString:_created_at]; //
当前时间NSDate *now = [NSDate date];// 日历对象 (方便比较两个日期之间的差距)NSCalendar *calendar =
[NSCalendar currentCalendar];// NSCalendarUnit 枚举代表想获得哪些差值NSCalendarUnit unit
= NSCalendarUnitYear | NSCalendarUnitWeekOfMonth | NSCalendarUnitDay |
NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;//
计算两个日期之间的差值NSDateComponents *cmps = [calendar components:unit
fromDate:createDate toDate:now options:0]; //
获得某个时间的年月日时分秒NSDateComponents *createDateCmps = [calendar components:unit
fromDate:createDate];NSDateComponents *nowCmps = [calendar components:unit
fromDate:now]; if (createDateCmps.year == nowCmps.year) { // 今年if
(cmps.day == 1) { // 昨天fmt.dateFormat = @"昨天 HH:mm";return [fmt
stringFromDate:createDate];} else if (cmps.day == 0){ // 今天if (cmps.hour >
1) { // 大于1小时前return [NSString stringWithFormat:@"%d小时前",
cmps.hour];}else if (cmps.minute >= 1) {return [NSString
stringWithFormat:@"%d分钟前", cmps.minute];}else {return @"刚刚";}}else
{ // 今年的其他日子fmt.dateFormat = @"MM-dd HH:mm";return [fmt
stringFromDate:createDate];}}else { // 非今年fmt.dateFormat = @"yyyy-MM-dd
HH:mm:ss";return [fmt stringFromDate:createDate];}
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之IOS频道!