Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
}
like image 636
Peggy Avatar asked Jan 27 '23 16:01

Peggy


1 Answers

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.
    }
like image 158
Roy Bernal Avatar answered May 16 '23 09:05

Roy Bernal