NSDateFormatter won't format strange date string

纵饮孤独 提交于 2019-12-02 05:03:11

问题


So I have a date string I receive that looks like this: "2013-03-20T21:13:26-7:00" that I receive from a web back end. I have no control over the back end, just a fyi.

My preference would be to have the date formatted like this: 9:13pm at 3/20.

When I do the following

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *date  = [dateFormatter dateFromString:@"2013-03-20T21:13:26-7:00"];

date is null.

My first thought is that the date string looks odd, and maybe I should remove the T and the "-7:00", as the "-7:00" is appended to every date I receive, and I'm not sure what it is for.

Even after the string looks like @"2013-03-20 21:13:26", date is still null.

I will admit I am not a pro at formatting dates, so if I could get some help with this issue, that would be great.

Thanks in advance!


回答1:


You have to set dateFormat to the dateFormatter

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssz"];
NSDate *date  = [dateFormatter dateFromString:@"2013-03-20T21:13:26-7:00"];

[dateFormatter setDateFormat:@"hh:mma 'at' MM/yy"];
NSString *dateString = [dateFormatter stringFromDate:date];



回答2:


Set the date format for the dateFormatter, your problem lies in the last part of the date, secondly you can set the T in the dateformatter as follows

  [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssz"];
  [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

  NSDate *date  = [dateFormatter dateFromString:@"2013-03-20T21:13:26-7:00"];



回答3:


Set dateFormat,

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


来源:https://stackoverflow.com/questions/15571801/nsdateformatter-wont-format-strange-date-string

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