当前位置:首页 > 通信资讯 > 正文

ios上次使用时间(ios时间代码)

本文实例为大家分享了iOS上次日期距离现在多久的计算代码,供大家参考,具体内容如下

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 /** * 计算上次日期距离现在多久 * * @param lastTime 上次日期(需要和格式对应) * @param format1 上次日期格式 * @param currentTime 最近日期(需要和格式对应) * @param format2 最近日期格式 * * @return xx分钟前、xx小时前、xx天前 */ + (NSString *)timeIntervalFromLastTime:(NSString *)lastTime lastTimeFormat:(NSString *)format1 ToCurrentTime:(NSString *)currentTime currentTimeFormat:(NSString *)format2{ //上次时间 NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init]; dateFormatter1.dateFormat = format1; NSDate *lastDate = [dateFormatter1 dateFromString:lastTime]; //当前时间 NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init]; dateFormatter2.dateFormat = format2; NSDate *currentDate = [dateFormatter2 dateFromString:currentTime]; return [Utilities timeIntervalFromLastTime:lastDate ToCurrentTime:currentDate]; } + (NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime{ NSTimeZone *timeZone = [NSTimeZone systemTimeZone]; //上次时间 NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]]; //当前时间 NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]]; //时间间隔 NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate]; //秒、分、小时、天、月、年 NSInteger minutes = intevalTime / 60; NSInteger hours = intevalTime / 60 / 60; NSInteger day = intevalTime / 60 / 60 / 24; NSInteger month = intevalTime / 60 / 60 / 24 / 30; NSInteger yers = intevalTime / 60 / 60 / 24 / 365; if (minutes <= 10) { return @"刚刚"; }else if (minutes < 60){ return [NSString stringWithFormat: @"%ld分钟前",(long)minutes]; }else if (hours < 24){ return [NSString stringWithFormat: @"%ld小时前",(long)hours]; }else if (day < 30){ return [NSString stringWithFormat: @"%ld天前",(long)day]; }else if (month < 12){ NSDateFormatter * df =[[NSDateFormatter alloc]init]; df.dateFormat = @"M月d日"; NSString * time = [df stringFromDate:lastDate]; return time; }else if (yers >= 1){ NSDateFormatter * df =[[NSDateFormatter alloc]init]; df.dateFormat = @"yyyy年M月d日"; NSString * time = [df stringFromDate:lastDate]; return time; } return @""; }

使用如下:

?
1 2 3 4 NSLog(@"\n\nresult: %@", [Utilities timeIntervalFromLastTime:@"2015年12月8日 15:50" lastTimeFormat:@"yyyy年MM月dd日 HH:mm" ToCurrentTime:@"2015/12/08 16:12" currentTimeFormat:@"yyyy/MM/dd HH:mm"]);

输出结果如下:

ios上次使用时间(ios时间代码)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。