Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift set default date to 10 years back

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.

like image 810
Moaz Khan Avatar asked Dec 14 '22 20:12

Moaz Khan


1 Answers

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.

like image 122
Usman Javed Avatar answered Dec 16 '22 10:12

Usman Javed