iOS常用于显示几小时前/几天前/几月前/几年前的代码片段
生活随笔
收集整理的这篇文章主要介绍了
iOS常用于显示几小时前/几天前/几月前/几年前的代码片段
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
/*** Retain a formated string with a real date string** @param dateString a real date string, which can be converted to a NSDate object** @return a string that will be x分钟前/x小时前/昨天/x天前/x个月前/x年前*/
+ (NSString *)timeInfoWithDateString:(NSString *)dateString {// 把日期字符串格式化为日期对象NSDate *date = [NSDate dateFromString:dateString withFormat:@"yyyy-MM-dd HH:mm:ss"];NSDate *curDate = [NSDate date];NSTimeInterval time = -[date timeIntervalSinceDate:curDate];int month = (int)([curDate getMonth] - [date getMonth]);int year = (int)([curDate getYear] - [date getYear]);int day = (int)([curDate getDay] - [date getDay]);NSTimeInterval retTime = 1.0;// 小于一小时if (time < 3600) {retTime = time / 60;retTime = retTime <= 0.0 ? 1.0 : retTime;return [NSString stringWithFormat:@"%.0f分钟前", retTime];}// 小于一天,也就是今天else if (time < 3600 * 24) {retTime = time / 3600;retTime = retTime <= 0.0 ? 1.0 : retTime;return [NSString stringWithFormat:@"%.0f小时前", retTime];}// 昨天else if (time < 3600 * 24 * 2) {return @"昨天";}// 第一个条件是同年,且相隔时间在一个月内// 第二个条件是隔年,对于隔年,只能是去年12月与今年1月这种情况else if ((abs(year) == 0 && abs(month) <= 1)|| (abs(year) == 1 && [curDate getMonth] == 1 && [date getMonth] == 12)) {int retDay = 0;// 同年if (year == 0) {// 同月if (month == 0) {retDay = day;}}if (retDay <= 0) {// 这里按月最大值来计算// 获取发布日期中,该月总共有多少天int totalDays = [NSDate daysInMonth:(int)[date getMonth] year:(int)[date getYear]];// 当前天数 + (发布日期月中的总天数-发布日期月中发布日,即等于距离今天的天数)retDay = (int)[curDate getDay] + (totalDays - (int)[date getDay]);if (retDay >= totalDays) {return [NSString stringWithFormat:@"%d个月前", (abs)(MAX(retDay / 31, 1))];}}return [NSString stringWithFormat:@"%d天前", (abs)(retDay)];} else {if (abs(year) <= 1) {if (year == 0) { // 同年return [NSString stringWithFormat:@"%d个月前", abs(month)];}// 相差一年int month = (int)[curDate getMonth];int preMonth = (int)[date getMonth];// 隔年,但同月,就作为满一年来计算if (month == 12 && preMonth == 12) {return @"1年前";}// 也不看,但非同月return [NSString stringWithFormat:@"%d个月前", (abs)(12 - preMonth + month)];}return [NSString stringWithFormat:@"%d年前", abs(year)];}return @"1小时前";
}
这里计算多少个月前时,为了减少计算量,没有分别获取对应月份的总天数,而是使用月份最大值31作为标准,因此,
如果需要更精准的计算,把对应的一小段代码替换掉即可
总结
以上是生活随笔为你收集整理的iOS常用于显示几小时前/几天前/几月前/几年前的代码片段的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 何德何能承蒙厚爱意思
- 下一篇: git show HEAD^num和个g