Hub3rt Hub3rt - 1 year ago 76
Objective-C Question

iOS 'dateFromString' Returning One Year Off

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.

Answer Source

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