问题
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.
回答1:
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.
回答2:
datePicker.date = Calendar.current.date(byAdding: .year, value: -10, to: Date())
来源:https://stackoverflow.com/questions/46149101/swift-set-default-date-to-10-years-back