Error converting string to date, with dateformatter in swift

1

In the user registry I have an input with a mask in this format "dd / MM / YY", after getting the input value, which comes as string, I have to convert it to date. The conversion always worked, only with the date 10/25/1992 that it's the problem and always returns nil. The code I'm using is this:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
if let dateString = birthDayInput.text { // 25/10/1992
   return dateFormatter.date(from: dateString) // nil
}

return nil
    
asked by anonymous 15.02.2018 / 17:17

1 answer

2

The problem occurs because of the way DateFormatter converts the date. When converting strings that have no defined time, DateFormatter takes midnight. Timezone is also inferred by device settings (in your case probably GMT-2).

In 1992, on October 25, began daylight saving time at midnight in Brazil. That is, the clock jumped from 10/24 23:59:59 to 10/25 01:00:00. Since there was no 25/10 00:00:00, the DateFormatter considers the date invalid. As you may be wondering, so does any other date when daylight savings time began at 00:00.

To know the start dates for daylight savings time you can check out this article .

This can be resolved by using the isLenient property, which causes the DateFormatter to use heuristics to infer the date to be converted.

dateFormatter.isLenient = true
    
15.02.2018 / 19:14