1

I now that there is a thread that discussing about minimum and maximum date time in here Minimum and maximum date in UIDatePicker

but I am a beginner now in programming, and I have little bit confused with date and time object. I have tried but I can't set up my date time picker properly. So I want to set my date time picker to have minimum and maximum limited time.

the minimum is Now, and the maximum is 1 month from now. what code do I have to use? Thanks in advance

https://i.stack.imgur.com/RxXUX.png

enter image description here

Alexa289
  • 8,089
  • 10
  • 74
  • 178

3 Answers3

1

You can try

self.datePicker.minimumDate = Date()

self.datePicker.maximumDate =  Calendar.current.date(byAdding: .day, value: 30 , to:Date())!

or

self.datePicker.maximumDate =  Calendar.current.date(byAdding: .month, value: 1 , to:Date())!
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
1

I recommend to use the date math skills of Calendar. It calculates the same day in the next month. If the day does not exist (for example Feb 30) it returns the next closest available date.

let now = Date()
let calendar = Calendar.current
let dayComponents = calendar.dateComponents([.day], from: now)
let maximumDate = calendar.nextDate(after: now, matching: dayComponents, matchingPolicy: .nextTime)
vadian
  • 274,689
  • 30
  • 353
  • 361
0

To get a Date exactly one month in the future from now (taking into account different month lengths), you can use Date.date(byAdding:value:to:), e.g. as in this answer. You'd take the result and set it as maximumDate of your picker.

dr_barto
  • 5,723
  • 3
  • 26
  • 47