11

Why is my NSDate time zone incorrect?

 3 years ago
source link: https://www.codesd.com/item/why-is-my-nsdate-time-zone-incorrect.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Why is my NSDate time zone incorrect?

advertisements

Here's the code:

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];

NSDate* newTime = [dateFormatter dateFromString:@"2011-10-19T12:22:07Z"];

[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormatter setDateFormat:@"dd-MMM-yyyy HHmm"];

NSString* finalTime = [dateFormatter stringFromDate:newTime];

The problem:

I'm in Toronto (EST, GMT-5). My final time SHOULD show 0722, I'm seeing 0822. Inspecting the objects I can see that newTime is '2011-10-19 08:22:07 EDT'. I'm not sure why that happens but it persists onto the finalTime string despite setting the dateFormatter time zone to systemTimeZone. I assume systemTimeZone is EDT then? Any insight into why this happens or how I can correct it would be greatly appreciated.

Thanks in advance.


A few things:

  1. Don't set the timezone on the date formatter. And then remove the quotes around the Z in the format string. This will allow the date formatter to determine the timezone from the actual date string.
  2. The output of 0822 is correct for your system timezone because you were on day light savings time on October 19th. On that date you were GMT-4, not GMT-5. In Canada, in 2011, DST ended on November 6th.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK