IOS how to set date format [duplicate]

删除回忆录丶 提交于 2019-11-29 19:17:18

问题


This question already has an answer here:

  • Converting an ISO 8601 timestamp into an NSDate: How does one deal with the UTC time offset? 5 answers

I have a string like this

NSString *datestr = @"2013-08-06T03:51:54+00:00";

I try to set dateformat as below:

NSDateFormatter *dformat = [[NSDateFormatter alloc]init];

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

NSDate *date = [dformat dateFromString:datestr];

But the date will be nil, so, can anyone tell me how to set the dateformat, thx!


回答1:


Try this:

 NSDateFormatter *dformat = [[NSDateFormatter alloc]init];

[dformat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];

NSDate *date = [dformat dateFromString:datestr];

Add ZZZ to the end of your formatter.




回答2:


Try out this code

NSString *datestr = @"2013-08-06T03:51:54+00:00";
NSDateFormatter *dformat = [[NSDateFormatter alloc]init];

[dformat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssz"];

NSDate *date = [dformat dateFromString:datestr];

use small z where z give you - with the specific non-location format. Where that is unavailable, falls back to localized GMT format. Use one to three letters for the short format or four for the full format. In the short format, metazone names are not used unless the commonlyUsed flag is on in the locale

for zone for more info about Date Format Patterns in objective c refer this link http://www.unicode.org/reports/tr35/tr35-19.html#Date_Format_Patterns hope this will help you




回答3:


try below:

NSString *dateString = @"2013-08-06T03:51:54+00:00";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";

NSDate *date;
NSError *error;
[formatter getObjectValue:&date forString:dateString range:nil error:&error];


来源:https://stackoverflow.com/questions/18098647/ios-how-to-set-date-format

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