Reputation: 31
datePicker.maximumDate = Date()
Will disable future date I want to restrict future year only.user can select future month and date. How to do this.any help will be appreciated.
Thanks in advance
Upvotes: 0
Views: 2909
Reputation: 131408
Get the current date and extract the year from it. (Use the Calendar function date(from:)
.) Create DateComponents for 31 December of that year. Use that to create a Date. Make that the maximum date for the date picker. That will let the user pick any date in the current year, but not advance the year.
Upvotes: 1
Reputation: 18581
I believe this is what you want:
let picker = UIDatePicker()
let calendar = Calendar.current
let currentYear = calendar.component(.year, from: Date())
guard let maximumDate = calendar.date(from: DateComponents(year: currentYear + 1))?.addingTimeInterval(-1) else {
fatalError("Couldn't get next year")
}
picker.maximumDate = maximumDate
print(picker.maximumDate ?? "")
The maximum date should be December 31st, 2018 at 23:59:59
in your date picker.
Upvotes: 4
Reputation: 54706
You can restrict the UIDatePicker
to only allow future dates in the current year, you can construct a Date
object corresponding to the start of next year and use that as the maximumDate
.
let thisYear = Calendar.current.component(.year, from: Date())
datePicker.maximumDate = Calendar.current.date(from: DateComponents(year: thisYear+1))
Upvotes: 1