NSDateFormatter dateFromString给出了错误的日期

时间:2021-12-28 15:38:15

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

我已经在其他类似的帖子里尝试过这些建议,但都没有效果。这是这句话的语境是:

I have an NSString like this:

NSString是这样的

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

But the resulting myDate variable holds this:

但由此得到的myDate变量包含以下内容:

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

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

有人知道为什么从dateFromString中选择了错误的日期吗?弦是11月18日,转换日期是12月31日…

Thanks everyone!

谢谢大家!

2 个解决方案

#1


48  

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

你需要使用yyyy作为一年,而不是yyyy。

From the Apple reference:

从苹果的参考:

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.

一个常见的错误是使用yyyyy。yyyyy指定日历年,yyyy指定在ISO年周日历中使用的年份(“年周”)。在大多数情况下,yyyyy和yyy产量相同,但是它们可能不同。通常您应该使用日历年。

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

为了正确,你还必须将EE改为EEE。尽管他们在我的测试中得出了相同的结果。

#2


1  

I think you need "EEE MMMM d, YYYY" i.e. triple E as format string. If this does not work, I recommend using hard coded strings with easier dates and formats to break down the problem. See for example NSDateFormatter not working for more hints on that topic.

我认为你需要"EEE MMMM d, YYYY"也就是三重E作为格式字符串。如果这不起作用,我建议使用具有更简单日期和格式的硬编码字符串来解决这个问题。请参见示例NSDateFormatter,该主题的更多提示无效。

#1


48  

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

你需要使用yyyy作为一年,而不是yyyy。

From the Apple reference:

从苹果的参考:

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.

一个常见的错误是使用yyyyy。yyyyy指定日历年,yyyy指定在ISO年周日历中使用的年份(“年周”)。在大多数情况下,yyyyy和yyy产量相同,但是它们可能不同。通常您应该使用日历年。

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

为了正确,你还必须将EE改为EEE。尽管他们在我的测试中得出了相同的结果。

#2


1  

I think you need "EEE MMMM d, YYYY" i.e. triple E as format string. If this does not work, I recommend using hard coded strings with easier dates and formats to break down the problem. See for example NSDateFormatter not working for more hints on that topic.

我认为你需要"EEE MMMM d, YYYY"也就是三重E作为格式字符串。如果这不起作用,我建议使用具有更简单日期和格式的硬编码字符串来解决这个问题。请参见示例NSDateFormatter,该主题的更多提示无效。