简体   繁体   English

NSDateFormatter dateFromString给出错误的日期

[英]NSDateFormatter dateFromString gives the wrong date

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? 有没有人知道为什么从dateFromString中挑出错误的日期? The string is November 18th, the converted date is December 31st... 该字符串是11月18日,转换日期是12月31日...

Thanks everyone! 感谢大家!

You need to use yyyy for the year, not YYYY . 你需要使用yyyy一年,而不是YYYY

From the Apple reference : 来自Apple参考

A common mistake is to use YYYY. 一个常见的错误是使用YYYY。 yyyy specifies the calendar year whereas YYYY specifies the year (of "Week of Year"), used in the ISO year-week calendar. yyyy指定日历年,而YYYY指定ISO年度日历中使用的年份(“年度周”)。 In most cases, yyyy and YYYY yield the same number, however they may be different. 在大多数情况下,yyyy和YYYY会产生相同的数字,但它们可能会有所不同。 Typically you should use the calendar year. 通常,您应该使用日历年。

And to be correct you also have to change EE to EEE . 为了正确,您还必须将EE更改为EEE Though they yield the same result in my test. 虽然他们在我的测试中产生了相同的结果。

I think you need "EEE MMMM d, YYYY" ie triple E as format string. 我认为你需要“EEE MMMM d,YYYY”,即三E作为格式字符串。 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. 例如,请参阅NSDateFormatter,以了解有关该主题的更多提示。

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

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