leonardloo
leonardloo

Reputation: 1803

Swift: Countdown from current time till a certain time

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.

Upvotes: 6

Views: 4096

Answers (2)

ivan123
ivan123

Reputation: 347

func tommorrow5() ->Date {
var todayAt5 = Calendar.current.dateComponents([.year,.month,.day,.hour], from: Date() )
todayAt5.hour = 17
let dateToDisplay = Calendar.current.date(from: todayAt5)
return Calendar.current.date(byAdding: .day , value: 1, to: dateToDisplay!)! }


func showTimeDifference()->DateComponents{
var todayAt5 = Calendar.current.dateComponents([.year,.month,.day,.hour], from: Date() )
todayAt5.hour = 17
let dateToDisplay = Calendar.current.date(from: todayAt5)
let now = Date()
switch now.compare(dateToDisplay!) {

case .orderedAscending : // now is earlier than 5pm

    return Calendar.current.dateComponents([Calendar.Component.hour, Calendar.Component.minute, Calendar.Component.second], from: Date(), to: dateToDisplay!)

case .orderedDescending : // now is later than 5 pm

    return Calendar.current.dateComponents([Calendar.Component.hour, Calendar.Component.minute, Calendar.Component.second], from: Date(), to: tommorrow5())
case .orderedSame : break // now is 5 pm
}


return Calendar.current.dateComponents([Calendar.Component.hour, Calendar.Component.minute, Calendar.Component.second], from: Date(), to: dateToDisplay!)

}

you can use it just like this it will return time to 5pm today if its already passed 5pm will return time to 5pm tomorrow

showTimeDifference()

Upvotes: -1

kennytm
kennytm

Reputation: 523224

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 

Upvotes: 26

Related Questions