NSDateFormatter generating weird UTC offset for pre-1900's date

I'm attempting to use an NSDateFormatter to format an NSDate into a specific format for communication with a server, but it seems like no matter what I do, a date that happens before 1/1/1900 ends up with a weird UTC offset. The dateFormat I'm specifying when I instantiate the formatter is: "yyyy-MM-dd'T'HH:mm:ssZ".


Here is the code I'm using to instantiate the NSDateFormatter:


NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];


Farther down the line, I am passing an NSDate into the NSDateFormatter's method call, stringFromDate like so:


NSString *formattedDate = [dateFormatter stringFromDate:myDateObj];


If I pass in an NSDate of "2018-07-17 15:00:00", it gets converted to "2018-08-17T15:00:00-0400". This string is in the desired format.


However, if I pass in an NSDate of "1825-07-17 15:00:00", it gets converted to "1825-07-17T15:00:00-045602". This string is not correct.


Can anyone help shed any light on this issue and how I might be able to resolve it?

Replies

What timezone are you using? The system handles time zone changes that happened in the past: https://stackoverflow.com/questions/37430032/nsdate-created-from-nsdatecomponents-incorrect

I tried running (more or less) your code here and the problem didn’t reproduce for me.

NSDate * d = [NSDate dateWithTimeIntervalSinceReferenceDate:-5536962000.0];
NSDateFormatter * df = [[NSDateFormatter alloc] init];
// df.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:-4 * 60 * 60];
df.dateFormat = @"yyyy'-'MM'-'dd'T'HH':'mm':'ssZ";
NSString * s = [df stringFromDate:d];
NSLog(@"'%@' -> '%@'", d, s);
// 'Sun Jul 17 18:58:45 1825' -> '1825-07-17T15:00:00-0400'

It’s hard to say what’s going on here for sure, but my best guess is that you’re being messed up by the locale. It’s not safe to use an

NSDateFormatter
for fixed-format dates without setting the locale to
en_US_POSIX
. Try running my code as is to see if it reproduces the problem. If it does, try uncommenting line 3.

You can learn more about the background to this in QA1480 NSDateFormatter and Internet Dates.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"