NSDateFormatter does not work with UTC

I have the following date: 2011-04-29T14: 54: 00-04: 00

When it executes the following code to convert it to a date, for some reason, the date is null:

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

SOLVE:

Ok, I figured it out. For some reason this method does not work.

 NSDate *date = [dateFormatter dateFromString:localDate]; 

It works. Hope this helps someone!

 NSError *error = nil; NSDate *date = nil; [dateFormatter getObjectValue:&date forString:localDate range:nil error:&error]; 
+2
source share
3 answers

Ok, I figured it out. For some reason this method does not work.

 NSDate *date = [dateFormatter dateFromString:localDate]; 

It works. Hope this helps someone!

 NSError *error = nil; NSDate *date = nil; [dateFormatter getObjectValue:&date forString:localDate range:nil error:&error]; 
+3
source

Try setting the time zone:

 dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; 

and you may need to quote: -s ,: s and Z in your format string (maybe not ... and :, but I think at least Z):

 [dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"]; 

Also, this is how my date formatter is configured, and it works great.

+2
source

NSDateFormatter apparently only implements canonical formats for time zones with "Z", as described in UTS No. 35 . With no leniency in analysis .

  • TimeZoneID +/- offset with hours and minutes separated by a colon, for example. 2011-04-29T14: 54: 00GMT-04: 00
  • +/- offset without separation between hours and minutes, for example. 2011-04-29T14: 54: 00-0400

Try changing the time zone format in your localDate string.

0
source

All Articles