我试图找出两个日期之间的差异。它返回的无效值为天。甚至它在几秒钟内返回错误的差异,导致无效的天数值。
(lldb) po earliest
▿ 2038-01-16 22:42:52 +0000
- timeIntervalSinceReferenceDate : 1168987372.695472
(lldb) po self
▿ 2038-02-16 22:42:52 +0000
- timeIntervalSinceReferenceDate : 1171665772.695472
(lldb) po Calendar.current.dateComponents([.second], from: earliest, to: self)
▿ second: 2678399 isLeapMonth: false
- second : 2678399
- isLeapMonth : false
以秒为单位的差异应为2678400
,我已经在一些在线日期差异网站上进行了检查。不确定为什么会出现这个奇怪的问题。
答案 0 :(得分:1)
将字符串日期转换为日期格式,并使用timeIntervalSince
计算它们之间的差异:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let timeAtPress = dateFormatter.date(from: "2038-01-16 22:42:52 +0000")
let timeAtPress2 = dateFormatter.date(from: "2038-02-16 22:42:52 +0000")
let elapsed = timeAtPress2?.timeIntervalSince(timeAtPress!)
print(elapsed!) //2678400.0
对我来说Calendar.current.dateComponents
也给出了相同的结果:
let elapsed2 = Calendar.current.dateComponents([.second], from: timeAtPress!, to: timeAtPress2!)
print(elapsed2) //second: 2678400 isLeapMonth: false