Question

Anyone know how to set the time zone in an NSDate object prior to iOS 4.0? In iOS 4 and greater I do the following:

NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekdayCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSTimeZoneCalendarUnit) fromDate:aDate];
NSTimeZone *gmt = [NSTimeZone timeZoneForSecondsFromGMT:0];
[components setTimeZone:gmt];
NSDate *newDate = [calendar dateFromComponents:components];

Problem is, setTimeZone and NSTimeZoneCalendarUnit are only available starting with iOS 4.0. Will I have to do a subtraction on the hours component?

Was it helpful?

Solution

NSCalendar has the method setTimeZone:

Available in iOS 2.0 and later.

Sets the time zone for the receiver.

- (void)setTimeZone:(NSTimeZone *)tz

Example:

NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"America/Jamaica"]];
NSLog(@"calendar timezone: %@", calendar.timeZone);

NSLog output:

calendar timezone: America/Jamaica (EST) offset -18000

or with a timezone offset:

NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSLog(@"calendar timezone: %@", calendar.timeZone);

NSLog output:

calendar timezone: GMT (GMT) offset 0

OTHER TIPS

You should use setTimeZone: on the NSCalendar object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top