OGeek|极客世界-中国程序员成长平台

标题: iphone - Why NSDate is reporting the wrong date? [打印本页]

作者: 菜鸟教程小白    时间: 2022-6-1 20:09
标题: iphone - Why NSDate is reporting the wrong date?

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?



Best Answer-推荐答案


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.






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4