简体   繁体   English

Swift中日期之间的天数

[英]Number of days between dates in Swift

I found a very strange behavior in Swift's Calendar dateComponents(_:from:to:) function. 我在Swift的Calendar 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)

This prints: 打印:

2018-04-21 19:58:16 +0000
2018-04-21 19:58:16 +0000
6
7

What am I missing? 我想念什么?

As Martin said in his comment, the problem is that you're getting a new value of Date() at each step, and the last value is a fraction of a second late than the first. 正如Martin在他的评论中所说,问题在于您在每个步骤上都获得了一个新的Date()值,而最后一个值要比第一个值晚一秒钟。

Note that this code gives the expected output: 请注意,此代码给出了预期的输出:

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)

It works because all the dates are EXACTLY the same value, not values that differ by a fraction of a second. 之所以有效,是因为所有日期都是完全相同的值,而不是相差几分之一秒的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM