skip to Main Content

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

Answers


  1. 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.

    Login or Signup to reply.
  2. You can try something like this:

    datePicker.maximumDate = Calendar.current.date(byAdding: .month, value: 3, to: Date())
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search