2

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.

sn8wman
  • 149
  • 1
  • 7

1 Answers1

2

Change your format string to: "MM/dd/yyyy" and it should work as written.

Capital "Y" in Unicode Technical Standard #35 Locale Data Markup Language refers to "week of year" based calendars in which the year transition occurs on a week boundary. For most applications you want lower case "y", which refers to standard numeric calendar year.

Robert
  • 6,660
  • 5
  • 39
  • 62