日曆計算
- components:fromDate:
返回一個 NSDateComponents 物件,該物件包含分解為指定元件的給定日期
NSCalendar *calender = [NSCalendar autoupdatingCurrentCalendar];
[calender setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSLog(@"%@",[calender components:NSCalendarUnitDay fromDate:[NSDate date]]);
NSLog(@"%@",[calender components:NSCalendarUnitYear fromDate:[NSDate date]]);
NSLog(@"%@",[calender components:NSCalendarUnitMonth fromDate:[NSDate date]]);
- components:fromDate:toDate:options:
使用指定元件作為 NSDateComponents 物件返回兩個提供日期之間的差異。
NSCalendar *calender = [NSCalendar autoupdatingCurrentCalendar];
[calender setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSLog(@"%@",[calender components:NSCalendarUnitYear fromDate:[NSDate dateWithTimeIntervalSince1970:0] toDate:[NSDate dateWithTimeIntervalSinceNow:18000] options:NSCalendarWrapComponents]);
- dateByAddingComponents:toDate:options:
返回一個新的 NSDate 物件,表示通過將給定元件新增到給定日期而計算的絕對時間。
NSCalendar *calender = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *dateComponent = [[NSDateComponents alloc]init];
[dateComponent setYear:10];
NSLog(@"%@",[calender dateByAddingComponents:dateComponent toDate:[NSDate dateWithTimeIntervalSinceNow:0] options:NSCalendarWrapComponents] );
- dateFromComponents:
返回一個新的 NSDate 物件,表示從給定元件計算的絕對時間。
NSCalendar *calender = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *dateComponent = [[NSDateComponents alloc]init];
[dateComponent setYear:2020];
NSLog(@"%@",[calender dateFromComponents:dateComponent]);