Amogh Talpallikar
Amogh Talpallikar

Reputation: 12184

dateFromString is returning nil

I know this probelm has been discussed many times on SO, but none of the results solve my problem. Here is the code snippet,

NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSZ"];         
NSDate* date = [df dateFromString:dateTaken]; 
/* dateTaken gets its value
 from the server as 2006-01-23T20:50:27Z */

I hav tried adding breakpoints and checked, dateFromString is returning nil. Once I get a date Object, I would change its format and display a different string but I am not getting a date Object itself.

What could be the issue here ?

Upvotes: 1

Views: 328

Answers (3)

dineshprasanna
dineshprasanna

Reputation: 1284

The retrieved format is wrong verify the format to convert

Upvotes: 0

Liron
Liron

Reputation: 2032

Seems that your formatter is wrong. It should be:
yyyy-MM-dd'T'HH:mm:ss'Z'
2006-01-23T20:50:27Z

Match it up to the string you have and there is no SSZ component.

EDIT:
After reviewing the other answer, I got nervous that mine was wrong, so I tried the following:
NSString* dateTaken = @"2006-01-23T20:50:27Z";
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SS'Z'"];
NSDate* date = [df dateFromString:dateTaken]; //nil
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
date = [df dateFromString:dateTaken]; // Not nil

Seems that with the string you provided, you need the 2nd format I just provided.

Upvotes: 1

user529758
user529758

Reputation:

The last part of the format string should be

SS'Z'

instead of

SSZ

Upvotes: 1

Related Questions