NSDateFormatter 没有意义

发布于 2024-12-21 20:16:12 字数 408 浏览 1 评论 0原文

我有以下日期:月= 12 月,日= 01,年= 2011。该日期以 NSString 形式给出,格式如下“111201”(YYMMdd)。现在我想用 NSDateFormatter 将此字符串解析为 NSDate 对象:

self.dateFormatter = [[NSDateFormatter alloc] init];
[self.dateFormatter setDateFormat:@"YYMMdd"];
NSDate* date = [self.dateFormatter dateFromString:strDate];

“111201”的输出是“2011-11-30 23:00:00 +0000”。这对我来说没有意义。

这怎么可能?我期望“2011-12-01 23:00:00 +0000”。

I have the following date: month = December, day = 01, year = 2011. The date is given as an NSString with the following format "111201" (YYMMdd). Now I want to parse this string into a NSDate object with a NSDateFormatter:

self.dateFormatter = [[NSDateFormatter alloc] init];
[self.dateFormatter setDateFormat:@"YYMMdd"];
NSDate* date = [self.dateFormatter dateFromString:strDate];

And the output of "111201" is "2011-11-30 23:00:00 +0000". That doesn't make sense to me.

How is this possible? I'd expect "2011-12-01 23:00:00 +0000".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怎樣才叫好 2024-12-28 20:16:12

当您在调试器中显示 NSDate 对象或通过 NSLog 输出其值时,它们始终显示为 GMT 日期和时间(这就是末尾的 +0000 的含义)。

您的本地时区显示为“+0100”(西欧?),因此日期格式化程序在“2011 年 12 月 1 日 00:00am +0100”运行并正确创建 NSDate。但在显示时,NSDate(这只是一个没有时区信息的单一时间点)以 GMT 形式显示 - 相当于提前一小时,即“2011 年 11 月 30 日 23:00pm +0000”。

如果您确实想将“111201”转换为“December 01 2011 00:00am +0000”,则将日期格式化程序的时区设置为 GMT,如下所示:

self.dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

When you display NSDate objects in the debugger or output their values via NSLog they are always shown as GMT dates and times (that's what the +0000 at the end means).

Your local time zone appears to be '+0100' (Western Europe?) so the date formatter is operating on 'December 01 2011 00:00am +0100' and creating an NSDate correctly. But at the point of display the NSDate (which is just a single point in time with no timezone information) is shown in GMT - and the equivalent is one hour earlier i.e. 'November 30 2011 23:00pm +0000'.

If you really want to convert '111201' to 'December 01 2011 00:00am +0000' then set the date formatter's timezone to GMT like this:

self.dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
夏见 2024-12-28 20:16:12

尝试将其添加到日期格式化程序中以更正 GMT 的时区:

self.dateFormatter.timeZone = [NSTimeZone systemTimeZone];

Try adding this to your date formatter to correct the time zone off of GMT:

self.dateFormatter.timeZone = [NSTimeZone systemTimeZone];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文