Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString to NSDate is giving the wrong day [duplicate]

I have this piece of code:

NSDateFormatter* df = [[NSDateFormatter alloc] init];
df.locale = [NSLocale currentLocale];
df.timeZone = [NSTimeZone localTimeZone];
df.timeStyle = NSDateFormatterShortStyle;
df.dateStyle = NSDateFormatterShortStyle;
df.locale = [NSLocale currentLocale];
[df setDateFormat:@"dd/MM/yyyy"];
NSString *todaysDate = @"31/12/2013";
NSDate* today = [df dateFromString:todaysDate];

NSLog(@"comparing todaysDate: %@ with today: %@",todaysDate,today);

When I check my console I see that todaysDate is 31/12/2013 and today is 2013-12-30 21:00:00 +0000 I do not understand why it goes 1 day into the past... can anyone help me out here? I'm trying to basically filter out some items in a dictionary based on date. Filtering part not included here as it was determined that the dateFromString is not doing its job.

like image 450
MikeS Avatar asked Mar 21 '23 04:03

MikeS


2 Answers

It's very probably because of your TimeZone. You seems to be GMT+3 or something like that. If you change your local Time Zone things should be ok.

You should use : df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]: instead of localTimeZoneto always have the same results even in different time zones.

like image 58
Zaphod Avatar answered Apr 05 '23 21:04

Zaphod


Add the below to your NSDateFormatter.

[df setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
like image 28
thatzprem Avatar answered Apr 05 '23 23:04

thatzprem