开发者

Why NSDate is reporting the wrong date?

开发者 https://www.devze.com 2023-03-21 19:16 出处:网络
Here is my code. NSDate *today = [NSDate date]; NSString *todayString = [[today description] substringToIndex:10];

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 pro开发者_运维问答blem?


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消