I want to get the minimum and maximum date from a date picker, but minimum date should be \"- 18\" of the current date and the maximum date should be \"- 100\" of current da
Swift 4.1
I have created my extension for all type of limit based on Calendar.Component
extension UIDatePicker {
func setLimit(forCalendarComponent component:Calendar.Component, minimumUnit min: Int, maximumUnit max: Int) {
let currentDate: Date = Date()
var calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian)
guard let timeZone = TimeZone(identifier: "UTC") else { return }
calendar.timeZone = timeZone
var components: DateComponents = DateComponents()
components.calendar = calendar
components.setValue(-min, for: component)
if let maxDate: Date = calendar.date(byAdding: components, to: currentDate) {
self.maximumDate = maxDate
}
components.setValue(-max, for: component)
if let minDate: Date = calendar.date(byAdding: components, to: currentDate) {
self.minimumDate = minDate
}
}
}
We can use this as following:
self.datePicker.setLimit(forCalendarComponent: .year, minimumUnit: 13, maximumUnit: 100)