Jody G
Jody G

Reputation: 583

NSDateFormatter not working properly with UTC

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

Answers (3)

Jody G
Jody G

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

monowerker
monowerker

Reputation: 2979

NSDateFormatter seems to only implement the canonical formats for timezones with 'Z' as described in UTS #35. With no leniency in parsing.

  1. TimeZoneID+/-offset with hours and minutes separated by colon, eg. 2011-04-29T14:54:00GMT-04:00
  2. +/-offset with no separation between hours and minutes, eg. 2011-04-29T14:54:00-0400

Try changing the format of the timezone in your localDate string.

Upvotes: 0

thefugal
thefugal

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

Related Questions