2

I'm using Xcode 8.0 and building on iOS 10 with Swift 3.

I have UIDatePicker in my view controller, connected as an outlet :

@IBOutlet weak var datePicker: UIDatePicker!

I'm trying to set maximum and minimum dates for it. The code I'm using :

self.datePicker.minimumDate = Date()
self.datePicker.maximumDate = Date(timeIntervalSinceNow: 60*60*24*365)
self.datePicker.datePickerMode = UIDatePickerMode.date

is not working - date picker can go infinitely back and forward in time.

Question is - what am I missing here?

Paweł
  • 1,201
  • 1
  • 14
  • 27
  • Where do you set these restrictions? (`init`, `viewDidLoad` etc.) – NSDmitry Dec 21 '16 at 12:26
  • I have same issue. After setting the minimumDate and maximumDate, reading those values back from the datePicker returns null (and the datePicker exists). Did you solve this? – Jeff Dec 09 '18 at 22:40

1 Answers1

0

I unfortunately suffered the same issue literally yesterday and after searching SO couldn't find a solution. I came up with my own implementation of max/min date to use in place of the built in one, it's not ideal, but it works.

func datePickerDidChangeDate(sender: UIDatePicker) {
    let maxDate = Date(timeIntervalSinceNow: 60*60*24*365)
    let minDate = Date()

    if sender.date.compare(minDate) == .orderedAscending || sender.date.compare(maxDate) == .orderedDescending {
        // Date is invalid
        sender.setDate(Date()) // Set selected date to now.
        return
    }
}

Also note doing the whole 60*60*24*365 is a bad idea and you should instead use NSCalendar.dateByAddingComponents but that is an entirely different question altogether.

Jacob King
  • 6,025
  • 4
  • 27
  • 45