斯威夫特:从当前时间倒计时到一定时间

leo*_*loo 3 nsdate ios swift

我正在尝试计算从现在开始的时间(即Date())到下一个下午5点.

如果当前时间是下午3点,输出将是02:00:00.(在HH:MM:SS)

如果当前时间是下午6点,则输出将是23:00:00.(直到下午5点!)

我如何在Swift 3中做到这一点?

谢谢.

ken*_*ytm 19

您可以Calendar.nextDate用来查找即将到来的下午5点的日期.

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)!
Run Code Online (Sandbox Code Playgroud)

然后,只计算不同next5pmnow使用之间的差异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 
Run Code Online (Sandbox Code Playgroud)