问题
I want to convert 2013-03-24T02:15:23-08:00 string to NSDate object . I tried formatter string yyyy-MM-ddTHH:mm:ss-Z , but the NSDate object is coming as nil. I know it is a trivial question but right now I am really stuck into it.
Below is my code for conversion
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-ddTHH:mm:ss-Z"];
NSDate* date = [dateFormatter dateFromString:image.dateTaken];
Kindly help.
回答1:
There are two errors in the date format string:
- The (literal)
T
character in the date format must be quoted as'T'
. - The format for a "ISO8601 time zone" like
-08:00
isZZZZZ
. Note that the minus sign is part of the time zone itself, not part of the format.
This should work:
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
回答2:
NSString *dateString = @"2013-03-24T02:15:23-08:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
回答3:
2013-03-24T02:15:23-08:00 in this string Z is not the correct format for -08:00...
The correct format for Z is as follows
Z : GMT-08:00
or
Z : -0800
Please check the below link for your reference
http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
If you change the date string to to -0800 or GMT-08:00 you can get the correct date...
来源:https://stackoverflow.com/questions/21522418/dateformatter-string-for-date-type-2013-03-24t021523-0800-objective-c