Thursday, June 13, 2013

NSCalendar dateFromComponents example in Objective C (iOS).

NSCalendar dateFromComponents

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

- (NSDate *)dateFromComponents:(NSDateComponents *)comps

The components from which to calculate the returned date.

Return Value of [NSCalendar dateFromComponents]
A new NSDate object representing the absolute time calculated from comps. Returns nil if the receiver cannot convert the components given in comps into an absolute time. The method also returns nil and for out-of-range values.

Discussion of [NSCalendar dateFromComponents]
When there are insufficient components provided to completely specify an absolute time, a calendar uses default values of its choice. When there is inconsistent information, a calendar may ignore some of the components parameters or the method may return nil. Unnecessary components are ignored (for example, Day takes precedence over Weekday and Weekday ordinals).

The following example shows how to use this method to create a date object to represent 14:10:00 on 6 January 1965, for a given calendar (gregorian).

NSCalendar dateFromComponents example.
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:1965];
[comps setMonth:1];
[comps setDay:6];
[comps setHour:14];
[comps setMinute:10];
[comps setSecond:0];
NSDate *date = [gregorian dateFromComponents:comps];
[comps release];
Note that some computations can take a relatively long time to perform.

Example of [NSCalendar dateFromComponents].
-(id) initWithISO8601Date: (NSString *) iso8601Date{
    // Takes a date in the YYYYMMDD form
    int year = [[iso8601Date substringWithRange:NSMakeRange(0, 4)] integerValue];
    int month = [[iso8601Date substringWithRange:NSMakeRange(4, 2)] integerValue];
    int day = [[iso8601Date substringWithRange:NSMakeRange(6,2)] integerValue];

    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setYear:year];
    [comps setMonth:month];
    [comps setDay:day];

    NSCalendar *cal = [NSCalendar currentCalendar];
    [cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
    self = [cal dateFromComponents:comps];

    [comps release];

    return self;


NSCalendar dateFromComponents example.
 NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setYear:2013];
    [components setMonth:1];
    [components setDay:1];

    NSDate *newDate = [calendar dateFromComponents:components];
    NSLog(@"%@",newDate); //2012-12-31 23:00:00 +0000

End of NSCalendar dateFromComponents example article.