简体   繁体   中英

Swift UIDatePicker restrict future year not month and date

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

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.

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))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM