简体   繁体   English

为什么我的NSDate时区不正确?

[英]Why is my NSDate timezone incorrect?

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). 我在多伦多(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'. 我的最后时间应该显示0722,我看到0822.检查对象我可以看到newTime是'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. 我不确定为什么会发生这种情况但是它仍然存在于finalTime字符串中,尽管将dateFormatter时区设置为systemTimeZone。 I assume systemTimeZone is EDT then? 我假设systemTimeZone是EDT呢? Any insight into why this happens or how I can correct it would be greatly appreciated. 任何洞察为什么会发生这种情况或如何纠正它将不胜感激。

Thanks in advance. 提前致谢。

You're currently in Toronto EST. 您目前在多伦多EST。 This time report you are getting back is showing EDT. 你回来的这个时间报告正在显示EDT。 Which is Eastern Daylight Time. 这是东部夏令时。 Make sure you subtract an hour for daylight savings time since it's EDT not EST. 确保你减去一个小时的夏令时,因为它是EDT而不是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
}

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. 然后删除格式字符串中Z周围的引号。 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. 0822的输出对于您的系统时区是正确的,因为您在10月19日的白天节省时间。 On that date you were GMT-4, not GMT-5. 那天你是GMT-4,而不是GMT-5。 In Canada, in 2011, DST ended on November 6th. 在加拿大,2011年,夏令时于11月6日结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM