社群類應用幾乎都需要「相對時間」顯示:剛剛、5 分鐘前、3 小時前、昨天、上週。這比直接印出 2015-07-08 19:09:39 友善得多。以下是一個可直接使用的 NSDate 分類實作。
// 物件方法:直接對 self 計算
- (NSString *)timeInfo {
return [NSDate timeInfoWithDate:self];
}
// 由 NSDate 出發,先轉成字串再走統一入口
+ (NSString *)timeInfoWithDate:(NSDate *)date {
return [self timeInfoWithDateString:
[self stringWithDate:date format:[self ymdHmsFormat]]];
}
+ (NSString *)timeInfoWithDateString:(NSString *)dateString {
NSDate *date = [self dateWithString:dateString format:[self ymdHmsFormat]];
NSDate *curDate = [NSDate date];
// 注意:這裡是 date - curDate,過去時間會是負值
NSTimeInterval time = -[date timeIntervalSinceDate:curDate];
int month = (int)([curDate month] - [date month]);
int year = (int)([curDate year] - [date year]);
int day = (int)([curDate day] - [date day]);
NSTimeInterval retTime = 1.0;
// 1. 小於一小時:顯示分鐘
if (time < 3600) {
retTime = time / 60;
retTime = retTime <= 0.0 ? 1.0 : retTime;
return [NSString stringWithFormat:@"%.0f 分鐘前", retTime];
}
// 2. 小於一天:顯示小時
else if (time < 3600 * 24) {
retTime = time / 3600;
retTime = retTime <= 0.0 ? 1.0 : retTime;
return [NSString stringWithFormat:@"%.0f 小時前", retTime];
}
// 3. 剛好落在前一天:顯示「昨天」
else if (time < 3600 * 24 * 2) {
return @"昨天";
}
// 4. 一個月以內:顯示天數
// 條件一:同年且相隔不超過一個月
// 條件二:跨年,且是去年 12 月 → 今年 1 月這種相鄰情形
else if ((abs(year) == 0 && abs(month) <= 1) ||
(abs(year) == 1 && [curDate month] == 1 && [date month] == 12)) {
int retDay = 0;
if (year == 0 && month == 0) {
retDay = day; // 同年同月,直接取日期差
}
if (retDay <= 0) {
// 取該月總天數,換算成距離今天的天數
int totalDays = (int)[self daysInMonth:date month:[date month]];
retDay = (int)[curDate day] + (totalDays - (int)[date day]);
}
return [NSString stringWithFormat:@"%d 天前", abs(retDay)];
}
// 5. 更久以前:顯示月或年
else {
if (abs(year) <= 1) {
if (year == 0) {
return [NSString stringWithFormat:@"%d 個月前", abs(month)];
}
// 跨年的情況
int month = (int)[curDate month];
int preMonth = (int)[date month];
// 跨年但同月,視為滿一年
if (month == 12 && preMonth == 12) {
return @"1 年前";
}
return [NSString stringWithFormat:@"%d 個月前",
abs(12 - preMonth + month)];
}
return [NSString stringWithFormat:@"%d 年前", abs(year)];
}
}
timeIntervalSinceDate 搭配月、年的粗略相減來判斷,遇到大小月和閏年時容易有邊界誤差。iOS 8 之後可以直接用 NSCalendar 的 components:fromDate:toDate:options: 取得精確的天、時、分差異,程式碼反而更短。abs(year) == 1 搭配月份比對來處理跨年,但沒排除「跨年且相隔超過一個月」的情形(例如去年 3 月到今天 1 月),會被誤判成「X 個月前」。改用 NSDateComponents 後這個問題自然消失。NSLocalizedString 並搭配 NSDateComponentsFormatter 的 relativeDateFormatter,系統會自動輸出各地區的慣用寫法。