如何在objective-c中解析ISO 8601日期

Cha*_*lis 4 iso objective-c nsdate

我需要从json创建一个NSDate,并以我从未使用过的格式创建日期.我要回来的日期字符串是2014-02-07T03:10:43.824Z.有谁知道我需要用于日期格式化程序的正确日期格式字符串?

Val*_*din 12

 NSDateFormatter *dateFormat = [NSDateFormatter new];
 //correcting format to include seconds and decimal place
 NSString* input = @"2014-02-07T03:10:59:434Z";
 dateFormat.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
 // Always use this locale when parsing fixed format date strings
 NSLocale* posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
 dateFormat.locale = posix;
 NSDate* output = [dateFormat dateFromString:input];
Run Code Online (Sandbox Code Playgroud)

  • 不,'Z'会逃脱Z角色,这不是我们想要的.时间戳中的Z是表示UTC时区的有效字符(请参阅[此处的UTC部分](http://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators)).这就是为什么[此SO帖子上的答案](http://stackoverflow.com/questions/5185230/converting-an-iso-8601-timestamp-into-an-nsdate-how-does-one-deal-with- -utc?lq = 1)使用Z,而不是'Z'. (3认同)
  • 这对我不起作用。对我有用的日期格式字符串是`yyyy-MM-dd'T'HH:mm:ss.SSSZ` (2认同)