【问题标题】:Wrong difference between dates日期之间的错误差异
【发布时间】:2018-02-17 06:05:49
【问题描述】:

我试图找出 2 个日期之间的差异。它返回几天的无效值。即使它以秒为单位返回错误的差异,也会导致无效的天数。

(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,我在一些在线日期差异网站上检查过这个。不知道为什么会发生这个奇怪的问题。

【问题讨论】:

  • Calendar.current.dateComponents([.day], from: early, to: date).day 显示 30,这是正确的。你期望什么价值?
  • 您需要将 timeIntervalSinceReferenceDate 打印到更多小数位,以说明您获得结果的原因。

标签: swift date


【解决方案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 

【讨论】:

    猜你喜欢
    • 2022-11-16
    • 2013-03-10
    • 2011-02-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 2014-04-21
    相关资源
    最近更新 更多