我试图计算从现在起(即日期())到下一个下午5点的时间。
如果当前时间是下午3点,则输出为02:00:00。 (在HH:MM:SS)
如果当前时间是下午6点,则输出将是23:00:00。 (直到下午5点!)
我如何在Swift 3中做到这一点?
感谢。
答案 0 :(得分:18)
您可以使用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)!
然后,使用dateComponents(_:from:to:)
计算next5pm
和now
之间的差异。
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
答案 1 :(得分:0)
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!)
}
你可以像这样使用它 它将返回到今天下午5点 如果它已经过了下午5点将返回到明天下午5点
showTimeDifference()