简体   繁体   中英

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

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?

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 (ie "'Week 'w' of 'Y").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM