我有UTC格式的字符串日期:
“2012-11-20T05:23:02.34”
现在我想为此使用UTC NSDate对象...并且实现了此功能。
+ (NSDate *)utcDateFromString:(NSString *)string withFormat:(NSString *)format {
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
inputFormatter.timeZone =[NSTimeZone timeZoneWithAbbreviation:@"UTC"];
[inputFormatter setDateFormat:format];
NSDate *date = [inputFormatter dateFromString:string];
[inputFormatter release];
return date;
}
并这样称呼它...
NSDate* submittedDate =[NSDate utcDateFromString:submittedDateString withFormat:@"YYYY-MM-dd'T'HH:mm:ss.SS"];
但这会返回NSDate描述。
2011-11-20 05:23:02 +0000
现在,如果您发现日期之间存在一年的差异...谁能解释为什么会这样。.?
谢谢你的帮助。
最佳答案
在dateformmater中,使用yyyy
而不是YYYY
它应该是
NSDate* submittedDate =[NSDate utcDateFromString:submittedDateString withFormat:@"yyyy-MM-dd'T'HH:mm:ss.SS"];
这样可以解决问题。
在以下链接中,搜索YYYY。
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html
它使用yyyy指定年份组成部分。一个常见的错误是使用YYYY。 yyyy指定日历年,而YYYY指定ISO年-周日历中使用的年份(“年中的一周”)。在大多数情况下,yyyy和YYYY产生相同的数字,但是它们可能不同。通常,您应该使用日历年。