Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateFormatter returning wrong year [duplicate]

Tags:

objective-c

I am using a pretty basic method to turn dates into strings.

+(NSString*)stringForDate:(NSDate*)date {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"ddMMYYYY"];
    NSLog(@"%@",date);
    NSLog(@"%@",[dateFormat stringFromDate:date]);
    return [dateFormat stringFromDate:date];
}

But some of them are coming back with the wrong years. Here's a sample of the log.

2014-05-25 00:26:46.050 App Name[1868:60b] 2013-12-26 16:00:00 +0000
2014-05-25 00:26:46.051 App Name[1868:60b] 27122013
2014-05-25 00:26:46.051 App Name[1868:60b] 2013-12-27 16:00:00 +0000
2014-05-25 00:26:46.051 App Name[1868:60b] 28122013
2014-05-25 00:26:46.051 App Name[1868:60b] 2013-12-28 16:00:00 +0000
2014-05-25 00:26:46.052 App Name[1868:60b] 29122014
2014-05-25 00:26:46.052 App Name[1868:60b] 2013-12-29 16:00:00 +0000
2014-05-25 00:26:46.054 App Name[1868:60b] 30122014

Ignore the fact that the days appear to be a day later - that's expected, due to time zone. However, all the dates being fed in are 2013, but some of the strings are coming back with 2014.

Any help appreciated - it's doing my head in!

like image 259
James White Avatar asked May 24 '14 16:05

James White


1 Answers

The thing is that YYYY and yyyy are two quite different things. You are using YYYY, which, as the docs tell you, is not necessarily the same as the calendar year.

like image 195
matt Avatar answered Nov 06 '22 03:11

matt