NSDateFormatter 错误的日期 [英] NSDateFormatter wrong date

查看:49
本文介绍了NSDateFormatter 错误的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就这么简单

     NSDateFormatter *df  = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"dd/MM/yyyy"];
     NSLog(@"Current date in event %@ %@",currentDate,[df stringFromDate:currentDate]);

但是在日志中

    Current date in event 2013-10-01 22:00:00 +0000 02/10/2013

为什么?

推荐答案

当您记录 NSDate 时,它总是以 UTC 时间打印.当您使用 stringFromDate: 时,除非您更改日期格式化程序的时区,否则您将获得本地时间的日期.

When you log an NSDate it always prints in UTC time. When you use stringFromDate: you get a date in local time unless you change the timezone of the date formatter.

在这种情况下,您所在的时区比 UTC 早两个小时(假设您在意大利).

In this case you are in a timezone two hours ahead of UTC (assuming you are in Italy).

由于 NSDate 对象是 2013 年 10 月 1 日 22:00 UTC,这与 2013 年 10 月 2 日午夜 UTC+2 相同.这就是为什么您会看到显示 10 月 2 日的字符串.

Since the NSDate object is October 1, 2013 at 22:00 UTC, this is the same as midnight of October 2, 2013 at UTC+2. This is why you see the string showing October 2.

这是另一种看待它的方式.您没有看到 1 天的差异.由于您的时区,您实际上看到了 2 小时的差异.从您的时间午夜到 0200 小时,您会看到 1 天的差异.

Here's another way to look at it. You are not seeing a 1 day difference. You are actually seeing a 2 hour difference due to your timezone. From midnight to 0200 hours your time, you will see what appears to be a 1 day difference.

这篇关于NSDateFormatter 错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆