我正在尝试转换一个看起来像这样的字符串(不确定是否完全正确的RFC3339格式):
2014-07-07T16:11:02.085Z
到NSDate。我环顾四周,尝试了多种格式,并使用Apple的代码进行转换。以下是我一直在尝试的格式:
@"yyyy'-'MM'-'dd'T'HH':'mm':'sss'Z'" //apples
@"yyyy-MM-dd'T'HH:mm:ss.'999Z'"
@"yyyy-MM-dd'T'HH:mm:ss.sss'Z'"
@"yyyy-MM-dd'T'HH:mm:ss"
我是怎么回事:
NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Convert the RFC 3339 date time string to an NSDate.
NSDate *date = [rfc3339DateFormatter dateFromString:@"2014-07-07T16:11:02.085Z"];
NSLog(@"date: = %@", date);
NSString *userVisibleDateTimeString;
if (date != nil) {
// Convert the date object to a user-visible date string.
NSDateFormatter *userVisibleDateFormatter = [[NSDateFormatter alloc] init];
assert(userVisibleDateFormatter != nil);
[userVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle];
[userVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];
userVisibleDateTimeString = [userVisibleDateFormatter stringFromDate:date];
}
NSLog(@"userVisibleDateTimeString = '%@'", userVisibleDateTimeString);
答案 0 :(得分:2)
你的第三次尝试几乎是正确的。日期格式应为
@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
资本" S"对于"小数秒"。