3

I need to get a Date object set for tomorrow at a certain time. I can figure out how to change the date to tomorrow but not how to set the time. Here is my function:

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!
}
checklist
  • 12,340
  • 15
  • 58
  • 102

2 Answers2

3

Pass the hours and mins to this function:

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

Anuraj
  • 1,242
  • 10
  • 25
  • 1
    Use DateComponents and not TimeInterval math if your dates really matter. You should not assume there are 24*60*60 seconds in every day. This code, for instance is off whenever a leap second is added to the current day. – Josh Homann Apr 19 '17 at 09:54
1
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)!
Chanchal Warde
  • 983
  • 5
  • 17