
日期與時間處理向來是 Objective-C 裡最囉嗦的一塊。DateTools 的靈感來自 DateTime 與 Time Period Library,目標就是讓這類操作變得直觀。
使用 CocoaPods:
pod 'DateTools'
DateTools 讓 NSDate 更容易取得年、月、日等各個組成部分。
類似 Twitter 的時間顯示,有完整與縮略兩種形式:
NSDate *timeAgoDate = [NSDate dateWithTimeIntervalSinceNow:-4]; NSLog(@"Time Ago: %@", timeAgoDate.timeAgoSinceNow); NSLog(@"Time Ago: %@", timeAgoDate.shortTimeAgoSinceNow); // 輸出: // Time Ago: 4 seconds ago // Time Ago: 4s // 若工程開啟國際化,且模擬器或真機語言設為簡體中文: // Time Ago: 4 秒鐘前 // Time Ago: 4 秒
只要工程支援國際化,DateTools 目前內建以下語言的在地化:ar(阿拉伯)、bg(保加利亞)、ca(加泰隆尼亞)、zh_Hans(簡體中文)、zh_Hant(繁體中文)、cs(捷克)、da(丹麥)、nl(荷蘭)、en(英文)、fi(芬蘭)、fr(法文)、de(德文)、gre(希臘)、gu(古吉拉特)、he(希伯來)、hi(印地)、hu(匈牙利)、is(冰島)、id(印尼)、it(義大利)、ja(日文)、ko(韓文)、lv(拉脫維亞)、ms(馬來)、nb(挪威)、pl(波蘭)、pt(葡萄牙)、ro(羅馬尼亞)、ru(俄文)、sl(斯洛維尼亞)、es(西班牙)、sv(瑞典)、th(泰文)、tr(土耳其)、uk(烏克蘭)、vi(越南)、cy(威爾斯)、hr(克羅埃西亞)。
NSDate *date = [NSDate date]; NSInteger year = date.year; NSInteger month = date.month; NSLog(@"year: %ld, month: %ld", (long)year, (long)month); // year: 2015, month: 9
若不想使用公曆,可以指定日曆:
NSInteger day = [date dayWithCalendar:calendar];
想換掉 DateTools 的預設日曆,改寫 NSDate+DateTools.m 中的 defaultCalendar 方法即可。
用 dateByAdding… 系列做年/月/日/時/分/秒的位移:
NSDate *date = [NSDate date]; NSInteger oldYear = date.year; NSDate *newDate = [date dateByAddingYears:1]; NSInteger newYear = newDate.year; NSLog(@"oldYear: %ld newYear: %ld", (long)oldYear, (long)newYear); // oldYear: 2015 newYear: 2016
以下方法回傳布林值,用來判斷先後:
若要取得具體差值:毫秒級間隔可直接用系統的 timeIntervalSinceDate: 與 timeIntervalSinceNow;年/月/週/日/時/分/秒則用 DateTools 的擴充方法。
NSInteger yearsApart = [firstDate yearsFrom:secondDate];
同類方法還有:
yearsFrom:、yearsUntil、yearsAgo、yearsEarlierThan:、yearsLaterThan:monthsFrom:、monthsUntil、monthsAgo、monthsEarlierThan:、monthsLaterThan:weeksFrom:、weeksUntil、weeksAgo、weeksEarlierThan:、weeksLaterThan:daysFrom:、daysUntil、daysAgo、daysEarlierThan:、daysLaterThan:hoursFrom:、hoursUntil、hoursAgo、hoursEarlierThan:、hoursLaterThan:minutesFrom:、minutesUntil、minutesAgo、minutesEarlierThan:、minutesLaterThan:secondsFrom:、secondsUntil、secondsAgo、secondsEarlierThan:、secondsLaterThan:NSDate *date = [NSDate date]; NSString *dateStr = [date formattedDateWithStyle:NSDateFormatterFullStyle]; // 實際內容會依裝置語言環境而異 NSLog(@"%@", dateStr); // 2015年9月25日 星期五 dateStr = [date formattedDateWithFormat:@"YYYY/MM/dd HH:mm:ss"]; NSLog(@"%@", dateStr); // 2015/09/25 15:19:23
DateTools 用 DTTimePeriod 類簡化時間段相關運算。
已知起訖時間:
DTTimePeriod *timePeriod = [[DTTimePeriod alloc] initWithStartDate:startDate endDate:endDate];
已知一端時間加上總長度:
// 從現在開始,長度 5 小時 DTTimePeriod *timePeriod = [DTTimePeriod timePeriodWithSize:DTTimePeriodSizeHour amount:5 startingAt:[NSDate date]];
hasStartDate:有起始時間則回傳 YEShasEndDate:有結束時間則回傳 YESisMoment:起訖時間相同(瞬間)則回傳 YESdurationIn…:回傳指定單位的時間段長度DTTimePeriod *timePeriod = [[DTTimePeriod alloc] initWithStartDate:date endDate:[date dateByAddingDays:10]]; NSLog(@"相差 %g 天", [timePeriod durationInDays]); // 相差 10 天
整體平移時,起訖時間會同步遷移:
shiftEarlierWithSize:amount: 整體前移shiftLaterWithSize:amount: 整體推後伸縮則是固定一端或中間錨點,改動另一端:
// 透過前移起始時間,把總長度從 1 分鐘拉長為 2 分鐘 DTTimePeriod *timePeriod = [DTTimePeriod timePeriodWithSize:DTTimePeriodSizeMinute endingAt:[NSDate date]]; [timePeriod lengthenWithAnchorDate:DTTimePeriodAnchorEnd size:DTTimePeriodSizeMinute amount:1];
下圖列出兩個時間段所有可能的關係:

可用下列方法判斷:
取得相對於另一時間段的關係:
-(DTTimePeriodRelation)relationToPeriod:(DTTimePeriod *)period;
所有可能的關係都定義在列舉 DTTimePeriodRelation 中。執行範例後點選 Time Periods,拖動滑桿可以很直觀地理解各種關係。

DateTools 提供兩種集合:DTTimePeriodCollection 允許存放彼此有交集的時間段;DTTimePeriodChain 則不允許。兩者的操作方式都很像 NSArray,可以新增、插入、移除,差別只在存放規則。它們的價值在於簡化「多個時間段」的邏輯運算——例如同一團隊為不同成員設定任務起訖時間,用 Collection 就能直接取得整個團隊任務的起點與終點。
規則較寬鬆,預設無序(順序與起訖時間無關)但支援手動排序,並能依內部內容推算出集合自身的起始與結束時間。它允許存放有交集的時間段。

// 建立集合
DTTimePeriodCollection *collection = [DTTimePeriodCollection collection];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY MM dd HH:mm:ss.SSS"];
DTTimePeriod *firstPeriod = [DTTimePeriod timePeriodWithStartDate:[dateFormatter dateFromString:@"2014 11 05 18:15:12.000"]
endDate:[dateFormatter dateFromString:@"2015 11 05 18:15:12.000"]];
DTTimePeriod *secondPeriod = [DTTimePeriod timePeriodWithStartDate:[dateFormatter dateFromString:@"2015 11 05 18:15:12.000"]
endDate:[dateFormatter dateFromString:@"2016 11 05 18:15:12.000"]];
[collection addTimePeriod:firstPeriod];
[collection addTimePeriod:secondPeriod];
firstPeriod = collection[0]; // 取出元素
排序方法分三類:
sortByStartAscending、sortByStartDescendingsortByEndAscending、sortByEndDescendingsortByDurationAscending、sortByDurationDescending操作方面,可以查詢某個 NSDate 或 DTTimePeriod 與集合的相對關係。例如 periodsIntersectedByDate: 會回傳一個新的 DTTimePeriodCollection,内含所有與該時間點有交集的時間段。更多方法見下圖:

Chain 以較嚴格的方式存放時間段:依起訖時間排列,且內部元素不允許有交集。它很適合用來建模連續會議、連續預約這類行程。

// 建立集合
DTTimePeriodChain *chain = [DTTimePeriodChain chain];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY MM dd HH:mm:ss.SSS"];
DTTimePeriod *firstPeriod = [DTTimePeriod timePeriodWithStartDate:[dateFormatter dateFromString:@"2014 11 05 18:15:12.000"]
endDate:[dateFormatter dateFromString:@"2015 11 05 18:15:12.000"]];
DTTimePeriod *secondPeriod = [DTTimePeriod timePeriodWithStartDate:[dateFormatter dateFromString:@"2015 11 05 18:15:12.000"]
endDate:[dateFormatter dateFromString:@"2016 11 05 18:15:12.000"]];
[chain addTimePeriod:firstPeriod];
// 若新加入的時間段與前一段無法完全銜接,Chain 會自動前移或後移,使時間軸保持緊湊
[chain addTimePeriod:secondPeriod];
firstPeriod = chain[0];
新加入的時間段長度不變,起始時間被對齊到前一段的結束時間,結束時間隨之平移;插入到非零位置時,其後的時間段會往後讓位;插入到零位置時,集合的起始時間往前移。
和 Collection 一樣,Chain 也支援相等性比較與整體平移,其他可用方法見下圖。
