Question

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.

Was it helpful?

Solution

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]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top