2016-10-06 122 views
1

我試圖計算從現在開始(即Date())到下一個下午5點的時間。Swift:從當前時間到某個時間倒數

如果當前時間是下午3點,輸出將是02:00:00。 (HH:MM:SS)

如果當前時間是晚上6點,輸出將是23:00:00。 (直到下一個下午5點!)

我該如何在Swift 3中做到這一點?

謝謝。

+1

我可以這一切都沒有絲毫原因? – Fattie

回答

14

您可以使用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:)計算next5pmnow之間的不同。

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 
+0

哇,完全踢$ –

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()