为什么 NSDate 报告错误的日期?

发布于 2024-11-25 08:31:54 字数 237 浏览 6 评论 0原文

这是我的代码。

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

我得到的是 2011-07-19 而不是 2011-07-18。关于可能出现的问题有什么想法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

゛清羽墨安 2024-12-02 08:31:54

NSDate 的 description 方法返回 UTC 时间,如果您在夏令时期间位于美国东部时区,则该时间比您的挂钟时间晚 4 小时。换句话说,按 UTC 时间计算,晚上 10 点您的时间就是第二天凌晨 2 点。

修复它的通常方法是使用 NSDateFormatter 相反,并在必要时显式设置时区。

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.

演出会有结束 2024-12-02 08:31:54
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:@"dd-MM-yyyy"];
NSString *dateString = [dateFormat stringFromDate:today];
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:@"dd-MM-yyyy"];
NSString *dateString = [dateFormat stringFromDate:today];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文