为什么无法使用NSDateFormatter正确解析此日期字符串? [英] Why can't I correctly parse this date string with NSDateFormatter?
问题描述
我试图解析一个由NSDateFormatter使用另一个具有相同格式的NSDateFormatter生成的字符串。
而不是试图使上一句有意义,这里有一些代码:
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(@\\\
now:|%@ | \\\
dateString:|%@ | \\\
parsed:|%@ |,now,dateString,parsed);
当我运行此代码时,我希望日期现在,但我得到以下输出:
现在:| 2009-05-04 18: 23:35 -0400 |
dateString:| 2009年5月4日18:23 |
parsed:| 2008-12-21 18:23:00 -0500 |任何人都有任何想法为什么会发生这种情况?解决方案 / div>您的问题是YYYY不是有效的ICU日期格式选项。
资本Y仅在使用周年周期选项(即'周'w'为'Y' )。
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 (i.e. "'Week 'w' of 'Y").
这篇关于为什么无法使用NSDateFormatter正确解析此日期字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文