NSString to NSDate conversion. Problem with "2011-08-24T14:06:10Z"
How to convert that string:
2011开发者_如何转开发-08-24T14:06:10Z
to NSDate using NSDateFormatter. I don´t know which format to set. What does this ´T´and ´Z´mean?
This is a RFC3339 date format.
You can parse it using:
NSDateFormatter* rfc3339DateFormatter = [[NSDateFormatter alloc] init];
[rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
NSDate* date = [rfc3339DateFormatter dateFromString:yourString];
[aDateFormatter release];
more information is available on the Apple Formatting Dates Documentation and you can also find more information on the RFC3339 date format (regarding the T and Z) in this section of the RFC3339 standard
The way to parse RFC 3339/ISO 8601 dates is as follows:
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZZZZZ";
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
Or, in macOS 10.12 and iOS 10:
NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
Then:
NSDate* date = [formatter dateFromString:dateString];
Note, the ZZZZZ
tells the formatter to use the time zone present in the string (where GMT+0 is represented as Z
) when converting strings to NSDate
objects. Likewise, by setting both the dateFormat
and the timeZone
, this formatter can also be used to convert NSDate
objects back into strings like 2011-08-24T14:06:10Z
, doing the necessary time zone conversions. Bottom line, this formatter works both directions.
The use of the locale
property is also best practice, as it ensures that the date will be properly interpreted regardless of the device's particular calendar (i.e. notably if it's not a Gregorian calendar). See Technical Q&A 1480.
精彩评论