Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Countdown from current time till a certain time

Tags:

ios

swift

nsdate

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.

like image 965
leonardloo Avatar asked Oct 06 '16 06:10

leonardloo


Video Answer


1 Answers

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 
like image 69
kennytm Avatar answered Oct 21 '22 11:10

kennytm