I am playing about with some timezone calculations and I have noticed quite an annoying error which is causing me problems.
If I create a date, use NSDateformatter to convert it to a certain time zone, retrieve that string, and then use dateformatter to convert the string back into a date object, it keeps reverting to my local GMT time.
Example
NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"COT"]];
NSString *str = [dateFormatter stringFromDate:date];
NSLog(@"%@", str);
//prints 2015-02-04 10:33:45 GMT-5
NSDate *newDate = [dateFormatter dateFromString:str];
NSLog(@"%@", newDate);
//Prints 2015-02-04 15:33:45 +0000
Why does it keep reverting back to GMT? I need that date object to accurately reflect the time zone I have set the dateformatter to for some testing purposes, so this is quite a frustrating issue.
Any help would be much appreciated
I believe that the problem is that NSDate
itself (i.e. the value you're logging at the end) doesn't have a time zone - it's just a moment in time. You're specifying the time zone *when formatting the value using stringFromDate*, and you're still using that when you *parse* the value back to an
NSDate... but the
NSDate` value itself doesn't remember the time zone.
To give a different example, imagine you had an IntegerFormatter
for NSInteger
, which let you say whether you wanted to format and parse in hex or decimal. You could format the decimal value 16 to 0x10, and then parse that value back... but the NSInteger
wouldn't "remember" that it was parsed from hex. It's exactly the same here - the time zone plays a part in the parsing (at least when the value itself doesn't specify the time zone) but it isn't part of the result in itself.
I need that date object to accurately reflect the time zone
Then you need to keep the time zone separately alongside the NSDate
, basically... (Looking at the documentation, it sounds like NSCalendarDate
did what you want, but that's deprecated.)
See more on this question at Stackoverflow