【发布时间】:2011-01-12 01:31:20
【问题描述】:
我有一个存储为自 1600 年 1 月 1 日以来我需要处理的天数的日期。这是一种遗留的日期格式,我需要在我的应用程序中多次阅读。
以前,我一直在创建日历、空日期组件和根日期,如下所示:
self.gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar
] autorelease];
id rootComponents = [[[NSDateComponents alloc] init] autorelease];
[rootComponents setYear: 1600];
[rootComponents setMonth: 1];
[rootComponents setDay: 1];
self.rootDate = [gregorian dateFromComponents: rootComponents];
self.offset = [[[NSDateComponents alloc] init] autorelease];
然后,为了稍后将整数转换为日期,我使用这个:
[offset setDay: theLegacyDate];
id eventDate = [gregorian dateByAddingComponents: offset
toDate: rootDate
options: 0];
(我从不在其他任何地方更改 offset 中的任何值。)
问题是我在 iOS 和 Mac OS X 上的 rootDate 时间不同。在 Mac OS X 上,我要到午夜了。在 iOS 上,我得到 8:12:28。 (到目前为止,这似乎是一致的。)当我添加天数后,奇怪的时间仍然存在。
在我的产品之前的版本中,我并不关心时间;现在我知道了。为什么在 iOS 上出现奇怪的时间,我该怎么办? (我假设小时差是 DST。)
我尝试将 rootComponents 的小时、分钟和秒设置为 0。这没有影响。如果我将它们设置为 0 以外的值,它会将它们添加到 8:12:28。我一直想知道这是否与闰秒或其他累积时钟变化有关。
或者这完全是在 iOS 上使用的错误方法?
【问题讨论】:
标签: cocoa-touch ios nsdate nscalendar nsdatecomponents