NSDateFormatter问题的日期和间隔精度

时间:2015-03-17 12:23:46

标签: ios cocoa swift nsdate nsdateformatter

当试图获取一天之后的最新可能日期(即2015-03-17 23:59:59.999 ......)时,我应该能够在该日期添加1天,并且然后从timeInterval double中减去最小精度的单位。这应该产生正确的日期,但是从下面可以看出,该日期的日期并不一致。

let calendar = NSCalendar.currentCalendar()
var comps = NSDateComponents()
comps.day = 17
comps.month = 3
comps.year = 2015

// Get today, tomorrow, and endOfToday
let today = calendar.dateFromComponents(comps)!
let tomorrow = calendar.dateByAddingUnit(.CalendarUnitDay, value: 1, toDate: today, options: nil)!
let intervalToday = today.timeIntervalSinceReferenceDate // 448243200
let intervalTomorrow = tomorrow.timeIntervalSinceReferenceDate // 448329600
// Get interval immediately before intervalTomorrow (subtract ULP - unit of least precision)
// nextafter intervalTomorrow in the direction of intervalToday
let endOfTodayInterval = nextafter(intervalTomorrow, intervalToday) // 448329599.9999999
let endOfToday = NSDate(timeIntervalSinceReferenceDate: endOfTodayInterval)

println(today) // 2015-03-17 00:00:00 +0000
println(tomorrow) // 2015-03-18 00:00:00 +0000
println(endOfToday) // 2015-03-18 00:00:00 +0000 !!! Hmm... should be 2015-03-17 23:59:59 +0000

// So... what day is the endOfToday!? 18th or 17th?
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "d"
dateFormatter.stringFromDate(endOfToday) // 18
calendar.component(.CalendarUnitDay, fromDate: endOfToday) // 17
// Hmm...

有谁知道这里到底发生了什么,以及为什么日期格式化程序和日历日期组件不同意?

请注意:有正当理由这个值需要比第二天低1个精度。我知道我可以减去1秒,但这不是被质疑的。有问题的是,为什么日期格式化程序认为下面的日期是18,应该是17。

0 个答案:

没有答案