Swift set default date to 10 years back

老子叫甜甜 提交于 2020-06-24 16:41:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!