Objective-C Language NSCalendar Calendrical Calculations


Example

- components:fromDate: Returns a NSDateComponents object containing a given date decomposed into specified components

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: Returns, as an NSDateComponents object using specified components, the difference between two supplied dates.

 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: Returns a new NSDate object representing the absolute time calculated by adding given components to a given date.

NSCalendar *calender = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *dateComponent = [[NSDateComponents alloc]init];
[dateComponent setYear:10];
NSLog(@"%@",[calender dateByAddingComponents:dateComponent toDate:[NSDate             dateWithTimeIntervalSinceNow:0] options:NSCalendarWrapComponents] );

- dateFromComponents: Returns a new NSDate object representing the absolute time calculated from given components.

NSCalendar *calender = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *dateComponent = [[NSDateComponents alloc]init];
[dateComponent setYear:2020];
NSLog(@"%@",[calender dateFromComponents:dateComponent]);