Arvinder Singh
Arvinder Singh

Reputation: 109

NSDateFormatter incorrect date conversion

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

Upvotes: 1

Views: 199

Answers (3)

iHulk
iHulk

Reputation: 4909

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.

Upvotes: 2

Abhishek
Abhishek

Reputation: 184

this might help you out. Add the following code.

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

Upvotes: 3

Jay Bhalani
Jay Bhalani

Reputation: 4171

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]);

Upvotes: 1

Related Questions