NSDateFormatter incorrect date conversion

211 Views Asked by At

I am using NSDateFormatter, to convert NSString to NSDate.

For e.g if my NSString value is Jun 24,2015 Then it is getting converted as 2015-06-23 18:30:00 +0000, which is incorrect.

It should be "24" instead of "23".

I am using below code to convert.

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMM dd,yyyy"];
NSLog(@"%@",[formatter dateFromString:strDate]);

Please help me to figure out the issue.

Thanks

3

There are 3 best solutions below

0
On BEST ANSWER

this might help you out. Add the following code.

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
2
On

Add line of NSTimeZone :

   NSString *dateString = @"Jun 24,2015";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMM dd,yyyy "];
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSLog(@"%@",[dateFormatter dateFromString:dateString]);
0
On

Your NSDateFormatter takes the value as local Date formate( IST, GMT +5:30) and then convert it to GMT. It take your value as 00:00 am, 24 june 2015 and convert it as according to GMT 18:30 23 june 2015 means 5 hours and 30 minutes before the actual time so just simply add

[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];

and it will work fine.