简体   繁体   中英

Number of days between dates in Swift

I found a very strange behavior in Swift's Calendar dateComponents(_:from:to:) function.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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