Thursday, June 13, 2013

NSCalendar setTimeZone example in Objective C (iOS).


NSCalendar setTimeZone

Sets the time zone for the receiver.

- (void)setTimeZone:(NSTimeZone *)tz

Parameters of [NSCalendar setTimeZone]
tz
The time zone for the receiver.

NSCalendar setTimeZone example.
 Setting the timezone of your NSCalendar to GMT before sending it dateFromComponents: will solve the issue.

[gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

Example of [NSCalendar setTimeZone].
You could also convert both NSDate objects to GMT. Like this:

NSDate *date;
NSTimeZone *timeZone;
NSDate *gmtDate = [date dateByAddingTimeInterval:-[timeZone secondsFromGMTForDate:date]];
And then set the NSCalendar's time zone to GMT. Like this:

NSCalendar *calendar;
[calendar setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0];

NSCalendar setTimeZone example.
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";

    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    [dateFormatter setTimeZone:gmt];
    NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
    [dateFormatter release];

End of NSCalendar setTimeZone example article.