Why can't I correctly parse this date string with NSDateFormatter?

社会主义新天地 提交于 2019-12-19 04:22:32

问题


I'm trying to parse a string that was generated by an NSDateFormatter using another NSDateFormatter with the same format.

Rather than trying to make that previous sentence make sense, here's some code:

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMM dd, YYYY HH:mm"];

NSDate *now = [[NSDate alloc] init];

NSString *dateString = [format stringFromDate:now];

NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setDateFormat:@"MMM dd, YYYY HH:mm"];

NSDate *parsed = [inFormat dateFromString:dateString];

NSLog(@"\n"
      "now:        |%@| \n"
      "dateString: |%@| \n"
      "parsed:     |%@|", now, dateString, parsed);

When I run this code, I expect that parsed would contain the same date as now but instead I get the following output:

now:        |2009-05-04 18:23:35 -0400| 
dateString: |May 04, 2009 18:23| 
parsed:     |2008-12-21 18:23:00 -0500|

Anybody have any ideas why this is happening?


回答1:


Your problem is that "YYYY" isn't a valid ICU date formatting option. You want "yyyy".

Capital 'Y' is only valid when used with the "week of year" option (i.e. "'Week 'w' of 'Y").



来源:https://stackoverflow.com/questions/822417/why-cant-i-correctly-parse-this-date-string-with-nsdateformatter

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