【发布时间】:2021-07-24 20:34:54
【问题描述】:
我正在实现一个计时器,该计时器需要计算用户处于非活动状态的毫秒数并计算差异并恢复计时器。由于 dateComponents 中没有毫秒选项,因此我使用了纳秒,但是,当我尝试计算两个日期之间的纳秒间隔时,每次都会得到相同的结果(当前日期正在改变,应该得到不同的结果),如果我改变纳秒到秒,它的工作原理。我执行了两次进行实验。
let d1 = Date()
let df = DateFormatter()
df.dateFormat = "y-MM-dd H:m:ss.SSSS"
let d2 = df.date(from: "2021-05-03 9:30:00.1234")!
print(df.string(from: d1))
print(df.string(from: d2))
print(Calendar.current.dateComponents([.second], from: d1, to: d2).second!)
// result1: "85573"
// result2: "85067"
当我使用纳秒时
let d1 = Date()
let df = DateFormatter()
df.dateFormat = "y-MM-dd H:m:ss.SSSS"
let d2 = df.date(from: "2021-05-03 9:30:00.1234")!
print(df.string(from: d1))
print(df.string(from: d2))
print(Calendar.current.dateComponents([.nanosecond], from: d1, to: d2).nanosecond!)
// result1: "2147483647"
// result2: "2147483647"
【问题讨论】:
标签: ios swift date nsdateformatter nsdatecomponents