Search code examples
objective-cnsdateformatterstring-to-datetime

NSDateFormatter not converting string to date


I'm using NSDateFormatter to convert a string to a date. However, the date returned is nil. It is only my hard-coded string that causes the problem. When I use stringFromDate: and convert this NSString to an NSDate it's fine.

Hard-coded date:
2012-30-22T10:30:19+0530
dateFromString:
2012-04-27T10:20:43+0530

I can see no difference in the date format.

Code:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZ"];

NSString *string = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"string %@", string);  

log: ~ string 2012-04-27T10:20:43+0530

NSDate *date = [dateFormatter dateFromString:string];
NSLog(@"date %@", date);

log: ~ date 2012-04-27 04:50:43 +0000

So far so good. A date is returned from my string. But when I try using a date which I've entered myself...

NSString *string2 = @"2012-30-22T10:30:19+0530";
NSLog(@"string2 %@", string2);

log: ~ date 2012-04-27 04:50:43 +0000

//Here comes the problem. 
NSDate *date2 = [dateFormatter dateFromString:string2];
NSLog(@"date 2 %@", date2);

log: ~ date 2 (null)

Why is this date null when the other date was not?


Solution

  • is the 30 in the month spot a typo in your self entered string? it might be screwing it up as it doesn't know a 30th month. Try typing your own valid date.