1

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?

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
user1060816
  • 75
  • 2
  • 6

2 Answers2

3

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
zaph
  • 111,848
  • 21
  • 189
  • 228
1

You should use setTimeZone: on the NSCalendar object.

Joshua Weinberg
  • 28,598
  • 2
  • 97
  • 90