I want to convert NSDate from one time zone to another.
Here is my code:
NSDate* convertTime(NSDate* fromDate, NSTimeZone* fromTimeZone, NSTimeZone* toTimeZone) {
if (fromTimeZone == toTimeZone) {
return fromDate;
}
NSCalendarUnit val = NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour| NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitTimeZone;
NSCalendar* dupCal = [[NSCalendar currentCalendar] copy];
[dupCal setTimeZone:toTimeZone];
NSDateComponents *dupComponents = [dupCal components:val fromDate:fromDate];
return [dupComponents date];
}
int testTimeZone() {
NSDate* res = convertTime([NSDate date], [NSTimeZone defaultTimeZone], [NSTimeZone timeZoneWithName:@"America/New_York"]);
NSLog(@"convertTime: %@", res);
return 0;
}
In the output window, I see this listing:
2014-02-15 11:15:18.040 MyApp[28742:70b] convertTime: (null)
For some reason, it return [dupComponents date];always returns nil, although I can clearly see in the debugger that it is correctly initialized. It contains the values that I expect.
Printing description of dupComponents:
<NSDateComponents: 0x100112260>
TimeZone: America/New_York (EST) offset -18000
Calendar Year: 2014
Month: 2
Leap month: no
Day: 14
Hour: 19
Minute: 19
Second: 29
Why is this so?
source
share