dateFormatter string for date type 2013-03-24T02:15:23-08:00 + objective C

我的未来我决定 提交于 2019-12-11 08:48:48

问题


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 is ZZZZZ. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!