Below is the string of time stamp which is returned by some server
dateFromServer = 2013-07-08 16:45:03Z
I am doing the following to convert it to an NSDate
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy'-'MM'-'dd' 'HH':'mm':'ss'Z'"];
NSTimeZone *destinationTimeZone = [NSTimeZone systemTimeZone];
[format setTimeZone:destinationTimeZone];
dateFromServer = [dateFromServer stringByReplacingOccurrencesOfString:@"T" withString:@" "];
NSDate *oldTime = [format dateFromString:dateFromServer];
and I am getting
oldTime is 2013-07-08 20:45:03 +0000
It looks like +4 is added to the original time stamp
Why does it do that, and how do I avoid this situation?
I personally do not know objective C but I do know the point of the problem. I'll try to guess along with the syntax.
When you receive 2013-07-08 16:45:03Z
the Z means UTC, or GMT+/-0000.
You are parsing it as a local timezone, or GMT-0400.
You then reemit it as reconverted into UTC with a 4 hour overcompensation.
To fix this, change:
NSTimeZone *destinationTimeZone = [NSTimeZone systemTimeZone];
to
NSTimeZone *destinationTimeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
Honestly, I'm not sure if you need to do any wrapping for the 0
to act as an NSInteger
but that's what you need.
You may have been intermittently missing this bug as a failure to determine time would have fallen back to the desired effect.
Out of curiosity, could someone comment as to whether my code is at least partially correct?