Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

iphone - 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:

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:

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

Thanks everyone!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to use yyyy for the year, not 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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...