NSDateFormatter won't format strange date stri

2019-02-26 18:20发布

问题:

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"];