How to set the time zone for a date in iOS 3.x
-
18-03-2021 - |
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?
La 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
Autres conseils
You should use setTimeZone:
on the NSCalendar
object.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow