NSDateFormatter wrong output with string from stringWithDate:
-
19-09-2019 - |
Question
Why does NSDateFormatter misinterpretes his own created dateString?
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-DD'T'HH:mm:ss.SSSZZZZ"];
NSDate *now = [NSDate date];
NSLog(@"Now: %@, Date: %@", [dateFormatter dateFromString:[dateFormatter stringFromDate:now]], now);
produces the following result: Now: 1970-01-06 18:07:05 +0100, Date: 2010-01-06 18:07:05 +0100
I know that you should use yyyy and dd (and it does not happen with yyyy and dd), but that's not the point here. I am expecting to receive the same date when parsing the string the formatter has created for me.
Solution
This will work
[dateFormatter setDateFormat:@"y-MM-DD'T'HH:mm:ss.SSSZZZZ"];
Look here, http://www.crystalminds.nl/?p=4 for more info about the difrent flags.
It seems like the formatter doesn't recognize any year when using YYYY because
[dateFormatter setDateFormat:@"YYYY-MM-DD'T'HH:mm:ss.SSSZZZZ"];
// is equal to
[dateFormatter setDateFormat:@"MM-DD'T'HH:mm:ss.SSSZZZZ"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow