NSDateFormatter dateFromString给出错误的日期 [英] NSDateFormatter dateFromString gives the wrong date

查看:477
本文介绍了NSDateFormatter dateFromString给出错误的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在其他类似的帖子中尝试了这些建议但没有用。情况如下:

I've already tried the suggestions in other posts similar to this with no avail. Here is the situation:

我有一个像这样的NSString:

I have an NSString like this:

Fri November 18, 2011

我试图将其转换为这样的日期:

and I am trying to convert that to a date like this:

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"EE MMMM d, YYYY"];
    NSDate *myDate = [df dateFromString: dateString];

但是生成的myDate变量保留了这个:

But the resulting myDate variable holds this:

2010-12-31 00:00:00 +0000



<有没有人知道为什么从dateFromString中挑出错误的日期?该字符串是11月18日,转换日期是12月31日......

Does anyone have any idea why the wrong date is being picked out from the dateFromString? The string is November 18th, the converted date is December 31st...

谢谢大家!

推荐答案

您需要使用 yyyy 作为年份,而不是 YYYY

You need to use yyyy for the year, not YYYY.

来自 Apple参考


常见的错误是使用YYYY。 yyyy指定日历年,而YYYY指定ISO年度日历中使用的年份(年度周)。在大多数情况下,yyyy和YYYY会产生相同的数字,但它们可能会有所不同。通常你应该使用日历年。

A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of "Week of Year"), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.

为了正确你还必须改变 EE EEE 。虽然他们在我的测试中产生了相同的结果。

And to be correct you also have to change EE to EEE. Though they yield the same result in my test.

这篇关于NSDateFormatter dateFromString给出错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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