I'm trying to calculate the time from now (i.e. Date()) till the next 5pm.
If the current time is 3pm, the output will be 02:00:00. (in HH:MM:SS)
If the current time is 6pm, the output will be 23:00:00. (until the next 5pm!)
How do I do that in Swift 3?
Thanks.
You can use Calendar.nextDate
to find the Date of the coming 5pm.
let now = Date()
let calendar = Calendar.current
let components = DateComponents(calendar: calendar, hour: 17) // <- 17:00 = 5pm
let next5pm = calendar.nextDate(after: now, matching: components, matchingPolicy: .nextTime)!
then, just compute the different between next5pm
and now
using dateComponents(_:from:to:)
.
let diff = calendar.dateComponents([.hour, .minute, .second], from: now, to: next5pm)
print(diff)
// Example outputs:
// hour: 2 minute: 21 second: 39 isLeapMonth: false
// hour: 23 minute: 20 second: 10 isLeapMonth: false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With