iOS常用于显示几小时前/几天前/几月前/几年前的代码片段
生活随笔
收集整理的這篇文章主要介紹了
iOS常用于显示几小时前/几天前/几月前/几年前的代码片段
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
/*** 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 @"昨天";}// 第一個條件是同年,且相隔時間在一個月內(nèi)// 第二個條件是隔年,對于隔年,只能是去年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) {// 這里按月最大值來計算// 獲取發(fā)布日期中,該月總共有多少天int totalDays = [NSDate daysInMonth:(int)[date getMonth] year:(int)[date getYear]];// 當(dāng)前天數(shù) + (發(fā)布日期月中的總天數(shù)-發(fā)布日期月中發(fā)布日,即等于距離今天的天數(shù))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小時前";
}
這里計算多少個月前時,為了減少計算量,沒有分別獲取對應(yīng)月份的總天數(shù),而是使用月份最大值31作為標(biāo)準(zhǔn),因此,
如果需要更精準(zhǔn)的計算,把對應(yīng)的一小段代碼替換掉即可
總結(jié)
以上是生活随笔為你收集整理的iOS常用于显示几小时前/几天前/几月前/几年前的代码片段的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 何德何能承蒙厚爱意思
- 下一篇: 盛世容颜下一句成语60句