Setting only specific months in UIDatePicker Swift 5

2.2k Views Asked by At

In my project i want to apply condition like, user can select date only 3months from current date.

I.e i want to display a date picker containing Month and Day with range of 90 days.

Eg. November is going on so only, November December January should be displayed in Date picker for picking.

How can i achieve that??

2

There are 2 best solutions below

4
On BEST ANSWER

You can try something like this:

datePicker.maximumDate = Calendar.current.date(byAdding: .month, value: 3, to: Date())
0
On

UIDatePicker has minimumDate and maximumDate properties. Use those to set the range of dates you want to allow the user to enter.


Edit:

@wonder posted code to calculate a date 3 months in the future:

futureDate = Calendar.current.date(byAdding: .month, value: 3, to: Date())

Alternately, you could add 90 days to the current date if that's what you want:

futureDate = Calendar.current.date(byAdding: .day, value: 90, to: Date())

Set the datePickerMode to .date to have the user choose only dates, not times.

I don't know how to remove the year selector, although if you select a date range of 90 days that all fall in the same year, they won't be able to select a year other than the current year.

(Note that starting in October, a date range of 90 days includes dates in 2 different years, so you would need the year anyway.)

As wonder said in a comment, you could create your own month and day picker using a UIPickerView, but you would need to add logic to change the number of days based on the month, and exclude days of the current month that are in the past.