Peggy
Peggy

Reputation: 372

How to set a minimum date to particular for date picker swift 4?

In swift 4, I have two textFields to set start day and end day and want to set "end day" picker the default is "start day" date and limit set the date which is earlier.

I can save start day's value from picker (datePick.date) and reference How to set a maximum date for date picker swift 4? to set datePick.minimumDate = startDay.

The picker default date is "start day" but it can set earlier day. I don't know how to change following code to limit it.

var sevenDaysfromNow: Date {
   return (Calendar.current as NSCalendar).date(byAdding: .day, value: 7, to: Date(), options: [])!
}

Is there possiable to set a minimum date to particular for date picker swift 4?

[update try to use Roy Bernal code]

func creatEndPicker(){
//...
let daysToSubtract = 10
        var dateComponent = DateComponents()
        dateComponent.day = daysToSubtract
        let earlierDate = Calendar.current.date(byAdding: dateComponent, to: start_Day)
        datePick.maximumDate = earlierDate 
        datePick.minimumDate = startDay 
}

Upvotes: 4

Views: 8766

Answers (2)

Roy Bernal
Roy Bernal

Reputation: 121

You can do it programmatically like Andy told you, with the picker view delegate, for instance you can put the next lines of code to get it, in your viewDidLoad or wherever you want to use the functionality:

override func viewDidLoad() {
        super.viewDidLoad()
        myDatePicker.datePickerMode = UIDatePickerMode.date // use date only
        let currentDate = NSDate()  //get the current date
        myDatePicker.minimumDate = currentDate  //set the current date/time as a minimum
        myDatePicker.date = currentDate //defaults to current time but shows how to use it.
    }

Upvotes: 8

Andy Lebowitz
Andy Lebowitz

Reputation: 1501

In the storyboard once you have a UIDatePicker on the screen, in the panel on the right in the attributes inspector you can check "Minimum Date" and set the minimum date there. I am sure this can also be done programmatically in which you may need to use the picker view delegate, but you should be fine doing it in the storyboard.

Upvotes: 0

Related Questions