即使正确设置了 NSTimezone 仍然有 NSDateFormatter 结果问题,为什么? [英] Still having NSDateFormatter result issues even with NSTimezone properly set, why?

查看:68
本文介绍了即使正确设置了 NSTimezone 仍然有 NSDateFormatter 结果问题,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结果仍然是前一天,我只是问自己为什么,因为 NSTimeZone 设置正确并且适合我的国家(意大利,罗马)这是我的代码存根,有什么想法吗?

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?

    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];

dateFromString 中的结果是 2008-07-02 22:00:00 +0000.

the result in dateFromString is this 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.

推荐答案

这是正确的,因为默认情况下 NSDate 将在其描述 +0000 中返回 UTC 日期.您比 UTC 早几个小时,因此您会获得前一天的 22:00:00.我是 -5 并且我的结果 UTC 是 2008-07-03 04:00:00 +0000 (DST).日期是正确的,它只是以 UTC 格式显示,如果您想在某处正确显示它,只需使用日期格式化程序再次获取字符串.

That is correct because by default the NSDate will return a UTC date in its description +0000. You are a couple of hours ahead of UTC so you get 22:00:00 for the day prior. I am -5 and my result UTC is 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.

...
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

这篇关于即使正确设置了 NSTimezone 仍然有 NSDateFormatter 结果问题,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆