Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateFormater - returns same year for 2015 and 2016 date [duplicate]

I have found a strange behaviour in NSDateFormatter with LLLL YYYY format, where it returns year 2015 for both 2015-01-01 and 2016-01-01 dates.

Am I missing something or is it a bug in the formatter class?

Code to reproduce:

NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = @"LLLL YYYY";

NSDate *d1 = [NSDate dateWithTimeIntervalSince1970:1420070400]; // 2015-01-01T00:00:00Z
NSDate *d2 = [NSDate dateWithTimeIntervalSince1970:1451606400]; // 2016-01-01T00:00:00Z

NSLog(@"%@ => %@", d1, [formatter stringFromDate:d1]); // 2015-01-01 00:00:00 +0000 => January 2015
NSLog(@"%@ => %@", d2, [formatter stringFromDate:d2]); // 2016-01-01 00:00:00 +0000 => January 2015

Both cases print "January 2015", but I would expect "January 2016" in the second case.

like image 457
Ondrej Hanak Avatar asked Dec 06 '25 00:12

Ondrej Hanak


2 Answers

You should use yyyy instead of YYYY, because YYYY is something different...

A deeper explanation from the docs:

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.

like image 184
Michael Avatar answered Dec 07 '25 12:12

Michael


You should use yyyy, not YYYY.

like image 41
Zachary Espiritu Avatar answered Dec 07 '25 12:12

Zachary Espiritu



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!