NSDateComponents 類在Foundation的日期和時(shí)間API中扮演著重要的角色察迟。其本身并沒有什么令人印象深刻的特征此洲,僅僅是一個(gè)日期信息的容器(信息包括:月,年,月中的某天炭玫,年中的某周卵凑,或者是否是閏月)庆聘。然而,值得一提的是勺卢,在其結(jié)合 NSCalendar和NSDateComponents 類之后伙判,日歷格式的轉(zhuǎn)換變得十分方便。
日期代表了時(shí)間中的某個(gè)特定時(shí)刻黑忱,而日期組件的表示則依賴于其所使用的日歷系統(tǒng)宴抚。很多時(shí)候,這個(gè)表示形式會和我們大多數(shù)人使用的Gregorian Calendar有著很大的不同甫煞。例如Islamic Calendar一年有354或者355天菇曲,而Buddhist calendar一年會有354,355抚吠,384或者385天羊娃。
從日期中提取日期組件
NSDateComponents類能夠被手動初始化,但是在大多數(shù)時(shí)候埃跷,會使用NSCalendar -components:fromDate:來提取某個(gè)日期的日期組件蕊玷。
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [NSDate date];
[calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit) fromDate:date];
其中components參數(shù)是一個(gè)用來獲取日期組件值的掩碼(bitmask)邮利,有下面這些值可以選擇:
NSEraCalendarUnit
NSYearCalendarUnit
NSMonthCalendarUnit
NSDayCalendarUnit
NSHourCalendarUnit
NSMinuteCalendarUnit
NSSecondCalendarUnit
NSWeekCalendarUnit
NSWeekdayCalendarUnit
NSWeekdayOrdinalCalendarUnit
NSQuarterCalendarUnit
NSWeekOfMonthCalendarUnit
NSWeekOfYearCalendarUnit
NSYearForWeekOfYearCalendarUnit
NSCalendarCalendarUnit
NSTimeZoneCalendarUnit
由于其計(jì)算所有可能值的開銷很大,所以隨后的計(jì)算只使用指定的值(用|來分割兩個(gè)不同的值垃帅,使用位運(yùn)算“或”操作)延届。
計(jì)算相對日期
NSDateComponents對象可以用來計(jì)算相對日期。使用 NSCalendar -dateByAddingComponents:toDate:options:方法來確定昨天贸诚,下周或者5小時(shí)30分鐘之后的日期方庭。
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [NSDate date];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setWeek:1];
[components setHour:12];
NSLog(@"1 week and twelve hours from now: %@", [calendar dateByAddingComponents:components toDate:date options:0]);
用Components來創(chuàng)建日期
NSDateComponents類最強(qiáng)大的特性也許就是能夠通過組件反向創(chuàng)建NSDate對象。NSCalendar -dateFromComponents:就是用來實(shí)現(xiàn)這個(gè)目的的:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:1987];
[components setMonth:3];
[components setDay:17];
[components setHour:14];
[components setMinute:20];
[components setSecond:0];
NSLog(@"Awesome time: %@", [calendar dateFromComponents:components]);
特別有意思的地方在于酱固,這個(gè)方法除了正常的月/日/年方式之外械念,也可以用某些信息來確定一個(gè)日期。只要提供的信息能夠唯一確定一個(gè)日期运悲,你就會得到一個(gè)結(jié)果龄减。例如:指定2013年的第316天,那么就會返回一個(gè)2013年12月11日0點(diǎn)0分0秒的NSDate對象(如果沒有指定時(shí)間班眯,時(shí)間組件的默認(rèn)值是0)希停。
請注意:如果傳入了一些前后矛盾的組件,那么就會返回一個(gè)丟失了信息的結(jié)果或者nil署隘。
NSDateComponents及它跟NSCalendar的關(guān)系突顯具有像Foundation一樣嚴(yán)格的工程框架的明顯優(yōu)勢宠能。你也許不會每天做日歷相關(guān)的計(jì)算,但當(dāng)有這樣的需要時(shí)磁餐,知道怎么使用NSDateComponents會讓你從無數(shù)挫折中解脫出來违崇。