Reputation: 583
I have the following date: 2011-04-29T14:54:00-04:00
When it runs through the following code to convert it to a date, the date is null for some reason:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *date = [dateFormatter dateFromString:localDate];
[dateFormatter release];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-mm-dd"];
NSLog(@"%@", [formatter stringFromDate:date]);
Any help would be appreciated
SOLVED:
Ok, I figured it out. For some reason, this method doesn't work.
NSDate *date = [dateFormatter dateFromString:localDate];
This works instead. Hope it helps someone!
NSError *error = nil;
NSDate *date = nil;
[dateFormatter getObjectValue:&date forString:localDate range:nil error:&error];
Upvotes: 2
Views: 2328
Reputation: 583
Ok, I figured it out. For some reason, this method doesn't work.
NSDate *date = [dateFormatter dateFromString:localDate];
This works instead. Hope it helps someone!
NSError *error = nil;
NSDate *date = nil;
[dateFormatter getObjectValue:&date forString:localDate range:nil error:&error];
Upvotes: 3
Reputation: 2979
NSDateFormatter seems to only implement the canonical formats for timezones with 'Z' as described in UTS #35. With no leniency in parsing.
Try changing the format of the timezone in your localDate string.
Upvotes: 0
Reputation: 1214
Try setting the timezone:
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
and you might need to quote the -'s, :'s, and the Z in your format string (maybe not the -'s and :'s, but I think at least the Z):
[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
Other than those, that is how my date formatter is configured and it works fine.
Upvotes: 2