Why is NSDate reporting an invalid date?

Here is my code.

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

I get 2011-07-19 instead of 2011-07-18. Any ideas on what could be the issue?

+4
source share
2 answers

The NSDate description method returns UTC time, which, if you are in the US eastern time zone during daylight saving time, is 4 hours later than your wall time. In other words, at 10 pm your time is 2 hours the next day at UTC.

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

+10
source
 NSDate *today = [NSDate date]; NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease]; [dateFormat setDateFormat:@"dd-MM-yyyy"]; NSString *dateString = [dateFormat stringFromDate:today]; 
+7
source

All Articles