NSDateFormatter wrong output with string from stringWithDate:

怎甘沉沦 提交于 2020-01-06 05:48:09

问题


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.


回答1:


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"];


来源:https://stackoverflow.com/questions/2014858/nsdateformatter-wrong-output-with-string-from-stringwithdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!