我在Swift的日历dateComponents(_:from:to :)函数中发现了一个非常奇怪的行为。
let a = Calendar.current.date(byAdding: DateComponents(day: 7), to: Date())!
let n1 = Calendar.current.dateComponents([.day], from: Date(), to: a).day!
let n2 = Calendar.current.dateComponents([.day], from: Date(), to: Calendar.current.date(byAdding: DateComponents(day: 7), to: Date())!).day!
print(a)
print(Calendar.current.date(byAdding: DateComponents(day: 7), to: Date())!)
print(n1)
print(n2)
打印:
2018-04-21 19:58:16 +0000
2018-04-21 19:58:16 +0000
6
7
我错过了什么?
答案 0 :(得分:0)
正如Martin在评论中所说,问题是你在每一步获得了一个新的Date()值,而最后一个值比第一个值迟了一小部分。
请注意,此代码提供了预期的输出:
let now = Date()
let a = Calendar.current.date(byAdding: DateComponents(day: 7), to: now)!
let n1 = Calendar.current.dateComponents([.day], from: now, to: a).day!
let n2 = Calendar.current.dateComponents([.day], from: now, to: Calendar.current.date(byAdding: DateComponents(day: 7), to: now)!).day!
print(a)
print(Calendar.current.date(byAdding: DateComponents(day: 7), to: now)!)
print(n1)
print(n2)
它的工作原理是因为所有日期都是完全相同的值,而不是相差几分之一的值。