iOS 'dateFromString' Returning One Year Of

2020-04-17 05:18发布

问题:

I am using the NSDateFormatter's dateFromString, yet when it is given the string '2013-03-06' it spits out an NSDate of '2012-03-06 00:00:00 CST'. The time is of no importance. I have the date format set to be exactly the same between the input and output.

I have an object which gets a date set using the code:

NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
NSDate* currentDate = [[NSDate alloc] init];

[dateFormat setDateFormat:@"YYYY-MM-dd"];
[self setMyValue:[dateFormat stringFromDate:currentDate]];

And then this value is later used to to set the date on a UIDatePicker:

NSDate *date = [[[NSDate alloc] init] autorelease];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

[dateFormat setDateFormat:@"YYYY-MM-dd"];

date = [dateFormat dateFromString:myFilter.myValue];

[datePicker setDate:date animated:YES];

Any pointers on where I am erring would be much appreciated.

回答1:

You should use yyyy and not YYYY.

From Data Formatting Guide:

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



回答2:

Change YYYY in the format to yyyy.



回答3:

Use yyyy instead of YYYY, to get the zero error while changing 'YEARS'.