Thursday, June 13, 2013

NSCalendar autoupdatingCurrentCalendar example in Objective C (iOS).


NSCalendar autoupdatingCurrentCalendar

Returns the current logical calendar for the current user.

+ (id)autoupdatingCurrentCalendar

Return Value
The current logical calendar for the current user.

Discussion of [NSCalendar autoupdatingCurrentCalendar]
Settings you get from this calendar do change as the user’s settings change (contrast with currentCalendar).

Note that if you cache values based on the calendar or related information those caches will of course not be automatically updated by the updating of the calendar object.

NSCalendar autoupdatingCurrentCalendar example.
NSDate *date = [NSDate date];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSUInteger preservedComponents = (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit);
date = [calendar dateFromComponents:[calendar components:preservedComponents fromDate:date]];

Example of [NSCalendar autoupdatingCurrentCalendar].
NSMutableArray *days = [[NSMutableArray alloc] init];
NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *tempCop = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
                                   fromDate:[NSDate date]];
NSDate *today = [cal dateFromComponents:tempCop];

for (int i = 0; i < 8; i++)
{
    NSDateComponents *comps = [[NSDateComponents alloc]init];
    [comps setDay:i];
    [days addObject:[cal dateByAddingComponents:comps toDate:today options:0]];    
}

NSCalendar autoupdatingCurrentCalendar example.
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

// Get the year, month and day of the current date
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit| NSDayCalendarUnit)] fromDate:[NSDate date];

// Extract the hour, minute and second components from self.timeOfDay
NSDateComponents *timeComponents = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:self.timeOfDay];

// Apply the time components to the components of the current day
dateComponents.hour = timeComponents.hour;
dateComponents.minute = timeComponents.minute;
dateComponents.second = timeComponents.second;

// Create a new date with both components merged
NSDate *currentDateWithTimeOfDay = [calendar dateFromComponents:dateComponents];

// Create new components to add to the merged date
NSDateComponents *futureComponents = [[NSDateComponents alloc] init];
dateComponents.day = [self.numberOfDays integerValue];
NSDate *newDate = [calendar dateByAddingComponents:futureComponents toDate:currentDateWithTimeOfDay options:0];

End of NSCalendar autoupdatingCurrentCalendar example article.