要從 NSDate 中取出年、月、星期、日、時、分、秒,靠的是 NSCalendar 搭配 NSDateComponents 的組合。但這條路有一個天生的限制:取不到毫秒。要拿到毫秒,得改用 NSDateFormatter 直接格式化輸出。
NSCalendar *calendar =
[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now;
NSDateComponents *comps = [[NSDateComponents alloc] init];
NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit
| NSDayCalendarUnit | NSWeekdayCalendarUnit
| NSHourCalendarUnit | NSMinuteCalendarUnit
| NSSecondCalendarUnit;
now = [NSDate date];
comps = [calendar components:unitFlags fromDate:now];
int year = [comps year];
int week = [comps weekday];
int month = [comps month];
int day = [comps day];
int hour = [comps hour];
int min = [comps minute];
int sec = [comps second];
關鍵在 unitFlags 這個位元遮罩:你放進去哪些單位,components: 就只計算並回傳哪些。全部列出來是為了取得完整資訊,實務上按需挑選即可,能省下一些運算。
要留意 weekday 的起點是 1(星期日),不是 0,這點和 C 語言的一些日期函式庫不同,很容易寫出差一天的 bug。
-(NSString *)NSDateToNSString:(NSDate *)nsDate {
// 注意:descriptionWithCalendarFormat: 屬於私有 API,
// 若要提交 App Store 請勿使用
// NSString *string = [nsDate descriptionWithCalendarFormat:@"%Y/%m/%d %H:%M:%S"
// timeZone:nil locale:nil];
NSDateFormatter *fmt = [[[NSDateFormatter alloc] init] autorelease];
// 只要時分秒與毫秒:
// [fmt setDateFormat:@"hh:mm:ss:SSS"];
[fmt setDateFormat:@"yyyy/MM/dd hh:mm:ss:SSS"];
NSString *string = [fmt stringFromDate:nsDate];
return string;
}
第一,SSS 就是毫秒。這也是為什麼要繞道 NSDateFormatter——NSDateComponents 根本不提供毫秒單位,只能從格式化字串下手。
第二,格式字串裡的 hh 與 HH 意思完全不同:hh 是 12 小時制(下午三點會顯示 03),HH 才是 24 小時制(顯示 15)。上面刻意保留 hh 是為了和原文一致,但在正式專案中請依需求改成 HH,否則上午與下午的時間會長得一模一樣。
最後,NSDateFormatter 的建立成本不低,如果在 cellForRowAtIndexPath: 這類高頻路徑中反覆建立,會明顯拖慢效能。實務上建議把它做成靜態物件或成員變數重複使用。
摘自 zcl369369的專欄