後端回傳的時間多半是 1970 年以來的秒數或毫秒數,畫面上要給使用者看的卻是可讀日期。以下整理四段常用程式碼。
- (NSString *)timeWithTimeIntervalString:(NSString *)timeString {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];
// 毫秒要除以 1000
NSDate *date = [NSDate dateWithTimeIntervalSince1970:
[timeString doubleValue] / 1000.0];
return [formatter stringFromDate:date];
}
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0]; NSTimeInterval a = [date timeIntervalSince1970] * 1000; // 乘 1000 為毫秒 NSString *timeString = [NSString stringWithFormat:@"%.0f", a];
- (void)getAgeWithDateString:(NSString *)date {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *createDate = [formatter dateFromString:date];
NSCalendar *gregorian =
[[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSUInteger unitFlags = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear;
NSDateComponents *components =
[gregorian components:unitFlags
fromDate:createDate
toDate:[NSDate date]
options:0];
NSInteger years = [components year];
NSInteger months = [components month];
NSInteger days = [components day];
}
時區。不指定 timeZone 時,formatter 會跟著系統設定跑。伺服器時間若固定是 UTC,最好明確寫死時區,否則使用者出國或手動改時區後,同一筆資料會顯示成不同時間。
秒與毫秒。判斷方式很簡單:位數 10 是秒,13 是毫秒。混用會直接跳到幾十年後,畫面上出現 57405 年這種笑話。
不要用 NSDate 做月級距的相減。timeIntervalSinceDate 回傳的是固定秒數,跨月、跨閏年會算錯。凡涉及「幾個月」「幾歲」,一律交給 NSCalendar 的 components 處理。