在Swift 3中设置明天的时间

问题描述:

我需要在某个特定时间为明天设置一个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://*.com/questions/36073704/how-to-change-the-current-days-hours-and-minutes-swift-2 – Larme

传递小时,分钟给这个函数:

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

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