Fix For NSDate Returning The Wrong Date and Time

Date manipulations look unobtrusive on the surface, however, given all the interesting nuances of dates (calendar types, leap years, day light savings, etc) even the simplest of calculations can lead to confusing results.

Check out this example:

// Get current date
NSDate *date = [NSDate date];
NSLog(@"Date 1: %@", date);

The output from the above returned:

Date 1: 2012-06-06 02:08:29 +0000

The problem is that when I ran this, the actual date and time was 2012-06-05 09:08:29. Seems NSDate uses GMT+0, whereas I live in GMT-5.

Here are two ways to get the correct results when creating a new NSDate object:

NSDateFormatter *DateFormatter=[[NSDateFormatter alloc] init]; 
[DateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];  
NSLog(@"Date 2: %@",[DateFormatter stringFromDate:[NSDate date]]);

Given that NSDateFormatter takes into consideration locale information, the correct date and time is returned: 2012-06-05 09:08:29

Another way to get the correct result follows:

NSLocale* currentLocale = [NSLocale currentLocale];
NSLog(@"Date 3: %@", [[NSDate date] descriptionWithLocale:currentLocale]);

The output is:

Tuesday, June 5, 2012 9:08:29 PM Central Daylight Time

Comments and suggestions for other options are welcome.

  1. or call this once upon start in AppDelegate:
    [NSTimeZone setDefaultTimeZone:[NSTimeZone timeZoneWithName:@”GMT”]]; //Europe/Berlin

  2. or call this once upon start in AppDelegate:
    [NSTimeZone setDefaultTimeZone:[NSTimeZone timeZoneWithName:@”Europe/Berlin”]];

  3. Use the class method localizedStringFromDate:dateStyle:timeStyle on NSDateFormatter

  4. thanks for this post, i was wondering why i kept getting tomorrows date for [NSDate date]

Comments are closed.