如果使用 Date(),为什么 2 个日期相差 1 分钟?

Why is difference between 2 Dates off by 1 minute if use Date()?

出于某种原因,当我使用Date()(获取当前日期)然后计算时差时,总是相差 1 分钟。但是,当我硬编码日期并计算时间差时,它是正确的。

这是为什么?我如何准确计算现在的日期(即 currentDate)和未来的日期(即 date2)之间的差异?

为了向您展示我的意思,这里有一个 playground 示例:

代码

let calendar = Calendar.current
var components = DateComponents()
components.day = 12
components.month = 2
components.year = 2017
components.hour = 19
components.minute = 50

let date1 = calendar.date(from: components)

components.hour = 20
components.minute = 30

let date2 = calendar.date(from: components)

let currentDate = Date()

let conversionInfoAccurate = Calendar.current.dateComponents([.hour, .minute, .day], from: date1!, to: date2!)
let daysAccurate = conversionInfoAccurate.day
let hoursAccurate = conversionInfoAccurate.hour
let minutesAccurate = conversionInfoAccurate.minute

let conversionInfo1Off = Calendar.current.dateComponents([.hour, .minute, .day], from: currentDate, to: date2!)
let days1Off = conversionInfo1Off.day
let hours1Off = conversionInfo1Off.hour
let minutes1Off = conversionInfo1Off.minute

Dates 具有毫秒级别的精度。除非您非常幸运,否则 Date() 的结果是您从组件构建的日期后 的某个毫秒数(甚至整秒)assert(date1 != currentDate)

然后当你求差时,分钟,还有一些秒数,从currentDate开始。您构造的日期恰好在分钟上,并且与另一个之间有整整 40 分钟。