NSDateFormatter MM/dd/yy problem with 2000 january 1

Am I doing something wrong or is it a bug? I am getting 21000 year when parsing 01/01/00 string to date using the "MM/dd/yy" format:


NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"MM/dd/yy"];

NSDate *originalDate = [NSDate dateWithTimeIntervalSinceReferenceDate:-24 * 60 * 60 * 366];

NSString *jan01String = [dateFormatter stringFromDate:originalDate];

NSDate *jan01Date = [dateFormatter dateFromString:jan01String];

NSLog(@"originalDate: %@, jan01String: %@, jan01Date: %@", originalDate, jan01String, jan01Date);


output:

2016-07-14 15:44:49.723 NSDateFormatterTests[5414:1537640] originalDate: 2000-01-01 00:00:00 +0000, jan01String: 01/01/00, jan01Date: 12099-12-31 22:00:00 +0000

Any time you're doing "24 * 60 * 60" when calculating dates you're doing it wrong. 🙂 We've got tons of WWDC content about how to do proper date calculations and formatting like this. A couple that speak directly to this issue:


Making Your App World-Ready

Solutions to Common Date and Time Challenges


But there are others from pretty much every year.


Having said that, your code isn't giving me the same weird 12099 result. When I copy/paste this on my Mac (running macOS Sierra), I get:


2016-07-14 07:09:27.885 DateFormatterTest[13138:2214820] originalDate: 2000-01-01 00:00:00 +0000, jan01String: 12/31/99, jan01Date: 1999-12-31 08:00:00 +0000


What OS and version are you running on?

Hm, interesting. I am on El Capitan 10.11.5 (15F34).

Well, as I see you are getting a different jan01String. (maybe due to the date operations that you mentioned). The problem appears when converting 01/01/00 string to date. I will simplify my sample code:


NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"MM/dd/yy"];

NSString *jan01String = @"01/01/00";

NSDate *jan01Date = [dateFormatter dateFromString:jan01String];

NSLog(@"jan01String: %@, jan01Date: %@", jan01String, jan01Date);


output:


2016-07-14 17:36:06.066 NSDateFormatterTests[7312:2177284] jan01String: 01/01/00, jan01Date: 12099-12-31 22:00:00 +0000

Amazing and sad that this bug still exists in the OS today.

The reason @pdm didn't reproduce the bug is because his timezone was likely set to +0 or less. Since it appears they work for Apple we're going to assume that their timezone is likely -7 or -8 depending on the time of year. The reason why it occurred for @BlixLT is because their timezone is +1 or greater.

This bug doesn't occur if one uses 4 digit years.

NSDateFormatter MM/dd/yy problem with 2000 january 1
 
 
Q