I want to set the default date of picker view to 10 years back from current date. The code I have so far is this.
let datePicker = UIDatePicker()
datePicker.datePickerMode = UIDatePickerMode.date
dateOfBirthTF.inputView = datePicker
datePicker.addTarget(self, action: #selector(changed),
for: .valueChanged)
to get value change
func changed(datePicker:UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = DateFormatter.Style.short
let strDate = dateFormatter.string(from: datePicker.date)
dateOfBirthTF.text = strDate
}
It sets the default date to current date perfectly but if I try to subtract a few years it doesn't work. Let me know the changes I need to do on this code to set the default date a few years back.
You can get 10 years back date using these lines of code.
let calendar = Calendar.current
let backDate = calendar.date(byAdding: .year, value: -10, to: Date())
print("\(backDate)")
-10
represent the number of years.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With