简体   繁体   English

即使正确设置了NSTimezone,仍然存在NSDateFormatter结果问题,为什么?

[英]Still having NSDateFormatter result issues even with NSTimezone properly set, why?

The result is still a day before, I'm just asking myself why, because the NSTimeZone is properly set and is the right one for my country (italy, rome) here's my stub of code, any ideas? 结果还是在前一天,我只是问自己为什么,因为NSTimeZone设置正确,并且是适合我的国家(意大利,罗马)的正确选择,这是我的代码清单,有什么想法吗?

    NSString *dateString = @"03/07/2008";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setFormatterBehavior:[NSDateFormatter defaultFormatterBehavior]];
    [formatter setDateFormat:@"dd/MM/yyyy"];
    [formatter setLocale:[NSLocale currentLocale]];
    [formatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSDate *dateFromString = [formatter dateFromString:dateString];
    [formatter release];

the result in dateFromString is this 2008-07-02 22:00:00 +0000 . dateFromString中的结果是此2008-07-02 22:00:00 +0000

I've looked for other solutions but the common answer was to set the timezone correctly, in my case it is set properly but the problem still remains. 我在寻找其他解决方案,但常见的答案是正确设置时区,就我而言,它的设置正确,但问题仍然存在。

That is correct because by default the NSDate will return a UTC date in its description +0000 . 这是正确的,因为默认情况下NSDate将在其描述+0000返回UTC日期。 You are a couple of hours ahead of UTC so you get 22:00:00 for the day prior. 您比UTC早了两个小时,因此前一天的时间为22:00:00。 I am -5 and my result UTC is 2008-07-03 04:00:00 +0000 (DST). 我是-5,我的结果UTC是2008-07-03 04:00:00 +0000 (DST)。 The date is correct, it is just being displayed in UTC, if you are trying to display it correctly somewhere just use the date formatter to get a string again. 日期是正确的,它只是在UTC中显示,如果您试图在某处正确显示它,只需使用日期格式器再次获取字符串即可。

...
NSDate *dateFromString = [formatter dateFromString:dateString];
NSString *stringFromDate = [formatter stringFromDate:dateFromString];
[formatter release];

NSLog(@"%@ : %@", dateFromString, stringFromDate);

2008-07-03 04:00:00 +0000 : 03/07/2008 2008-07-03 04:00:00 +0000:03/07/2008

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

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