Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 886
Hub3rt Avatar asked Aug 27 '26 11:08

Hub3rt


1 Answers

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

like image 132
trojanfoe Avatar answered Aug 30 '26 03:08

trojanfoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!