0

I have this string date:

2014-04-21T07:55:13Z

when I convert that to NSDate I have the hour like 6:55... 1 hours less. WHY?

This is the code I am using to convert:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *newDate = [dateFormatter dateFromString:dateStr];

newDate is now 2014-04-21 06:55:13 +0000 !!!???

what is wrong?

NOTE: That one hour less would make sense if the date was my local time (GMT+1) being converted to GMT. But if that Z is zero offset ( = GMT) the date is already GMT.

Duck
  • 34,902
  • 47
  • 248
  • 470
  • Have a look at this post. http://stackoverflow.com/questions/12033892/converting-date-of-format-yyyy-mm-ddthhmmss-sss – rustylepord Apr 21 '14 at 08:04

1 Answers1

1

I don't think your code is wrong. using this code:-

NSString *dateStr = @"2014-04-21T07:55:13Z";

// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *date = [dateFormat dateFromString:dateStr];

 NSLog(@" date log %@",date); //2014-04-21 02:25:13 +0000 output

// Convert date object to desired output format
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
dateStr = [dateFormat stringFromDate:date];

NSLog(@"string %@",dateStr);  //2014-04-21T07:55:13Z output

but NSLog of NSDATE is not output correct according to this NSDate Format outputting wrong date so your code is right.

The NSDate doesn't know anything about formatting (just date information), and the NSDateFormatter doesnt really know anything about dates, just how to format them. So you have to use methods like -stringFromDate: for know that is current or not to actually format the date for pretty human-readable display.

NSLog(@" date is %@",[dateFormat stringFromDate:date]);
Community
  • 1
  • 1
Nitin Gohel
  • 49,482
  • 17
  • 105
  • 144
  • my date contains a Z, meaning that it is already GMT0, now can NSDate convert to GMT a date that is already GMT. I first thought NSDate was considering my local timezone that is GMT+1 but then I verified that when it converts that date that is already GMT to GMT, it subtracts one hour. In other words, it is converting a GMT date to GMT by converting it to GMT-1!!!!!!!! – Duck Apr 21 '14 at 08:55
  • You are right by mysterious ways I verified now that you should not **EVER** – and I cannot put that bold enough – trust NSDate for anything. – Duck Apr 21 '14 at 09:11