Date formatter subtracting year by one and changing day when converting from string to date

Viewed 588

I'm using dateformatter to convert a date between string and date types for inputing a date via a UIDatePicker. When the view loads if a saved string of the date exists it's put into the date text field (and entered correctly). When dateformatter converts the string into a date it returns the wrong date. (Always December 20ish of the previous year.)

let df = DateFormatter()
df.dateFormat = "MM/dd/YYYY"

func setDatePickerDate() {
    if dobText.text != "" {
        print("\n\nSaved date as string: \(dobText.text!)")
        let testDate = df.date(from:dobText.text!)
        print("Saved date converted to date: \(testDate!)")
        print("Date converted back to string: \(df.string(from: testDate!))")
        dobPicker?.date = df.date(from: dobText.text!)!
    }
}

Which returns:

Saved date as string: 06/07/1977 Saved date converted to date: 1976-12-19 06:00:00 +0000 Date converted back to string: 12/19/1976

and if I keep running the setDatePicker function it keeps subtracting a year and changing the day.

Saved date as string: 12/19/1976 Saved date converted to date: 1975-12-21 06:00:00 +0000 Date converted back to string: 12/21/1975

Saved date as string: 12/21/1975 Saved date converted to date: 1974-12-22 06:00:00 +0000 Date converted back to string: 12/22/1974

Etc.

edit: Just noticed it cycles the days between 19-25 adding 1 to the date until it hits 25 then returning back to 19.

1 Answers
Related