0

I'm trying to use an NSDatePicker to set a time when an event should happen. Unfortunately, however, this control is used to set a complete date and therefore it is possible that when I have to use the value, it belongs to the past. My goal is to use the datePicker to set a time in the future.

enter image description here

To create a future date preserving this time I tried to set a loop that adds a day until we get to a future point but this seems to be very expensive in terms of time and processing, or I tried to manually build a date using only time. Unfortunately, I do not think I have found a viable solution because of my lack of experience on the subject.

Here is the code I am using:

// getting date value from a NSDatePicker
let date = myDatePicker.dateValue

// learn if the date is in future or in past
if date.timeIntervalSince(currentDate as Date).sign == FloatingPointSign.minus {

    print("\(date) is in past") // update adding days to make it in future

    // get the hour and minute from the date
    let timeFormatter = DateFormatter()
    timeFormatter.dateFormat = "HH:mm" // only hour and second
    let timeString = timeFormatter.string(from: date as Date)

    print("\(timeString)") // here I get "18:10" or "6:10 PM" based on system preferences (12 or 24)

    // create a date in future that use this hours

} else {

    // the date is already in future, just use it
    ...
}

I found several questions here on Stack Overflow, that are helping me to better understand how to use NSDateFormatter and also a great online tutorial http://www.knowstack.com/swift-nsdateformatter/. I also found some questions that seems similar to mine, like: returns a date an hour in the future and init] returning date an hour in the past? but they did not help me.

Apple Developer Documentation: NSDatePicker NSDateFormatter

Cue
  • 2,952
  • 3
  • 33
  • 54
  • 1
    See [Problem combining a date and a time into a single NSDate](https://stackoverflow.com/questions/5979462/problem-combining-a-date-and-a-time-into-a-single-nsdate) – Willeke Jan 16 '19 at 12:35
  • Thank you Willeke, this will help me a lot. – Cue Jan 17 '19 at 16:24

0 Answers0