设置NSDateComponents会导致NSDate不正确 [英] Setting NSDateComponents results in incorrect NSDate

查看:136
本文介绍了设置NSDateComponents会导致NSDate不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取一个21:00作为当地时间的NSDate对象 - 不关心哪一天。我对这个非常奇怪的结果感到头疼:

I'm trying to get an NSDate object that has 21:00 as the local time - don't care about what day. I'm scratching my head at this very strange result:

NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setHour:21];
[components setMinute:0];
[components setSecond:0];

NSDate *date = [calendar dateFromComponents:components];
NSLog(@"%@", date);

结果是 0001-01-02 04:52:58 +0000

我不知道为什么。当前时间是太平洋标准时间17:34,但结果不会随当地时间而变化。

I have no idea why. The current time is 17:34 PST, but the result doesn't change with the local time.

如果我将setMinute和setSecond行调整为

If I adjust the setMinute and setSecond lines to

[components setMinute:7];
[components setSecond:2];

我得到 0001-01-02 05:00:00 +0000 ,这是正确的(太平洋标准时间21:00)。

I get 0001-01-02 05:00:00 +0000, which is correct (21:00 PST).

推荐答案

问题是铁路时间不是'实施到1883年11月18日。你忽略了设定一年,所以你要在那之前得到一个约会。在实施铁路时间之前,美国时区与格林威治标准时间的确不同。我不确定Apple为你选择了什么时区,但是在1883年搬到太平洋标准时,似乎已经调整了7分2秒。

The problem is that railroad time wasn't implemented until November 18, 1883. You're neglecting to set a year so you're getting a date before that. Prior to the implementation of railroad time, the US time zones weren't exact hour differences from GMT. I'm not sure exactly what time zone Apple selects for you but whichever it was seems to have been adjusted by 7 minutes and 2 seconds upon the move to PST in 1883.

这篇关于设置NSDateComponents会导致NSDate不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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