-5

I am creating an alarm clock app for IOS. Long story short, I have configured the DatePicker to display only hours and minutes.

My problem is that When the user inputs 6:00 AM, I want it to be for the following morning, where Xcode now is assuming it is the same day.

EX: The user goes to sleep at 10 pm on a Wednesday and sets his alarm for 6:00 AM Thursday. My app is assuming the 6:00 AM is meant for Wednesday. How can I fix this?

shallowThought
  • 18,342
  • 7
  • 61
  • 106
  • What research have you done so far? What code have you written? This question has all the information you need to solve your issue (for example: create a date component to add 1 to the day): https://stackoverflow.com/q/24089999/558933 – Robotic Cat Jul 23 '17 at 19:44

2 Answers2

0

The most reliable way to get the next occurrence of a time is nextDate(after:matching:matchingPolicy: of Calendar because it considers also daylight saving changes.

assuming datePicker is the NSDatePicker instance:

let date = datePicker.date

let calendar = Calendar.current
// get hour and minute components of the given date
let components = calendar.dateComponents([.hour, .minute], from: date)
// calculate the next occurrence of the date components from now
let nextOccurrence = calendar.nextDate(after: Date(), matching: components, matchingPolicy: .nextTime)
vadian
  • 253,546
  • 28
  • 306
  • 323
0

I like using the AFDateHelper library personally.

import AFDateHelper

let tomorrowDate = dateFromPicker.adjust(.day, offset: 1)
anders
  • 4,091
  • 2
  • 22
  • 31