2017-04-19 60 views
2

我需要在某個特定時間爲明天設置一個Date對象。我可以想出如何將日期更改爲明天,但不知道如何設置時間。這裏是我的功能:在Swift 3中設置明天的時間

func getTomorrowAt(hour: Int, minutes: Int) -> Date { 
    let calendar = Calendar.current 
    var date = calendar.date(byAdding: .day, value: 1, to: Date()) 

    // here I need to set the time to hour:minutes 


    return date! 
} 
+0

你可以用'(NS)DateComponents'了點。例如,你可以設置你想要的日期Date()'(now),然後像你一樣添加1天。 – Larme

+0

如何讓DateComponenets獲得今天的日期和特定的時間? – checklist

+0

http://stackoverflow.com/questions/36073704/how-to-change-the-current-days-hours-and-minutes-swift-2 – Larme

回答

1

傳遞小時,分鐘給這個函數:

func getTomorrowAt(hour: Int, minutes: Int) -> Date { 
let today = Date() 
let morrow = Calendar.current.date(byAdding: .day, value: 1, to: today) 
return Calendar.current.date(bySettingHour: hour, minute: minutes, second: 0, of: morrow) 

} 

enter image description here

+1

使用DateComponents而不是TimeInterval數學如果你的日期真的很重要。你不應該假設每天有24 * 60 * 60秒。例如,當閏秒添加到當前日期時,該代碼就會關閉。 –

+0

@JoshHomann我編輯了答案 – Anuraj

0
let greg = Calendar(identifier: .gregorian) 
let now = Date() 
var components = greg.dateComponents([.year, .month, .day, .hour, .minute, .second], from: now) 
components.hour = 10 
components.minute = 35 
components.second = 0 

let date = greg.date(from: components)!