dateFromString returns nil after using rfc3339date

2019-09-05 00:12发布

问题:

I am trying to get NSDate from NSString by parsing in following manner:

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'Z'"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSString *createdString = [NSString stringWithFormat:@"2014-08-27T17:10:36.000+05:30"];
NSDate *createdDate = [rfc3339DateFormatter dateFromString:createdString];

Here createdDate is being returned as nil. What am I missing here? Also please clarify me proper usage of timeZone and locale.

回答1:

You are not using Right Date Formatter

Use This Line:

[rfc3339DateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"];

in Place of this:

[rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];