Thursday, June 13, 2013

NSCalendar components fromDate example in Objective C (iOS).

NSCalendar components fromDate

Returns a NSDateComponents object containing a given date decomposed into specified components.

- (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)date

The components into which to decompose date—a bitwise OR of NSCalendarUnit constants.
The date for which to perform the calculation.

Return Value of [NSCalendar components fromDate]
An NSDateComponents object containing date decomposed into the components specified by unitFlags. Returns nil if date falls outside of the defined range of the receiver or if the computation cannot be performed

Discussion of [NSCalendar components fromDate]
The Weekday ordinality, when requested, refers to the next larger (than Week) of the requested units. Some computations can take a relatively long time.

The following example shows how to use this method to determine the current year, month, and day, using an existing calendar (gregorian):

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:date];

NSCalendar components fromDate example.
+(NSDateComponents *)getComponentFromDate:(NSDate *)date {

    NSCalendar * gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekdayCalendarUnit | NSDayCalendarUnit;
    NSDateComponents* components = [gregorian components:unitFlags fromDate:date];

    NSTimeZone* timeZone = [NSTimeZone localTimeZone];
    if(timeZone.isDaylightSavingTime) components.hour = ((int)timeZone.daylightSavingTimeOffset/3600);

    [gregorian release];

    return components;

Example of [NSCalendar components fromDate].
NSDate *today = [NSDate date];
NSLog(@"Today's date: %@",today);

unsigned hourAndMinuteFlags = NSHourCalendarUnit | NSMinuteCalendarUnit;
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
NSDateComponents* travelDateTimeComponents = [calendar components:hourAndMinuteFlags fromDate:today];
NSString* hours = [NSString stringWithFormat:@"%02i", [travelDateTimeComponents hour]];
NSString* minutes = [NSString stringWithFormat:@"%02i", [travelDateTimeComponents minute]];

NSLog(@"Calendar: %@",calendar);
NSLog(@"Travel Components: %@",travelDateTimeComponents);
NSLog(@"Hours: %@",hours);
NSLog(@"Minutes: %@",minutes);

NSCalendar components fromDate example.
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];

    int year = [components year];
    int month = [components month];
    int day = [components day];

    return year;

End of NSCalendar components fromDate example article.