문제

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.

도움이 되었습니까?

해결책 2

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.

다른 팁

You're currently in Toronto EST. This time report you are getting back is showing EDT. Which is Eastern Daylight Time. Make sure you subtract an hour for daylight savings time since it's EDT not EST.


I'm out right now so I can't test this code but I think this should work:

NSDate *currentDate = [NSDate date];
NSTimeZone *currentZone = [NSTimeZone localTimeZone]; 

if ([currentZone isDaylightSavingTimeForDate:currentDate]) {
   //adjust the time by 1 hour here
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top