自 macOS 10.10 起,蘋果棄用了舊式 NSDate 日期元件存取方法(如 dateComponents:fromDate: 舊版重載),推薦使用 NSCalendar 的 getEra:year:month:day:fromDate: 與 getHour:minute:second:nanosecond:fromDate: 方法。本文示範正確、高效的現代寫法。
/* 取得目前日期時間物件 */
NSDate *dateNow = [NSDate date];
/* 必須使用 currentCalendar 初始化,不可用 alloc/init,
否則取得的時間會異常 */
NSCalendar *calendar = [NSCalendar currentCalendar];
/* 準備接收元件的變數(皆為 NSInteger,64 位相容) */
NSInteger year, month, day;
NSInteger hour, minute, second, nanosecond;
/* 一次取得時、分、秒、奈秒 */
[calendar getHour:&hour minute:&minute second:&second nanosecond:&nanosecond fromDate:dateNow];
/* 取得紀元、年、月、日(紀元固定為 1 即公元) */
[calendar getEra:NULL year:&year month:&month day:&day fromDate:dateNow];
/* 格式化輸出(%ld 為 64 位整數,%02ld 不足兩位補零) */
NSLog(@"%04ld-%02ld-%02ld %02ld:%02ld:%02ld.%03ld",
year, month, day, hour, minute, second, nanosecond / 1000000);
/* 輸出範例:2015-03-26 13:44:34.582 */
[NSCalendar currentCalendar],否則時間會亂碼。& 取址,函式會直接寫入變數記憶體位址。nanosecond / 1000000 取得毫秒部分(三位數)。%04ld、%02ld 確保位數對齊補零。[[NSCalendar alloc] init] 導致時間隨機錯誤& 取址導致編譯錯誤或執行崩潰%d 列印 NSInteger 在 64 位環境下截斷採用此現代 API,不僅符合蘋果最新規範,程式碼也更清晰、效能更佳,是目前 iOS/macOS 開發的標準作法。