Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why NSDate is reporting the wrong date?

Tags:

iphone

nsdate

Here is my code.

NSDate *today = [NSDate date];        
NSString *todayString = [[today description] substringToIndex:10];
NSLog(@"Today: %@", todayString);

I am getting 2011-07-19 instead of 2011-07-18. Any ideas on what may be the problem?

like image 510
David Avatar asked Jul 19 '11 02:07

David


2 Answers

NSDate's description method returns times in UTC, which if you are in the US Eastern Time Zone during daylight savings time is 4 hours later than your wall clock time. In other words, at 10pm your time it is 2am the next day in UTC.

The usual way to fix it is to use NSDateFormatter instead, and explicitly set the time zone if necessary.

like image 122
Anomie Avatar answered Nov 15 '22 10:11

Anomie


NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:@"dd-MM-yyyy"];
NSString *dateString = [dateFormat stringFromDate:today];
like image 39
Ayush Goel Avatar answered Nov 15 '22 11:11

Ayush Goel