Error when converting string to date, with dateformatter in Swift

Asked

Viewed 233 times

1

In user registration I have an input with a mask in this format "dd/MM/YY", after taking the value of the input, which comes as a string, I have to convert it to date. The conversion always worked, only with the date 25/10/1992 it of 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

1 answer

2


The problem occurs due to the way that Dateformatter converts the date. When converting strings that have no time set, Dateformatter midnight. Timezone is also inferred by device settings (in your case probably GMT-2).

It turns out that in 1992, on 25/10 began in Brazil the daylight saving time, at midnight. That is, the watch jumped from 24/10 23:59:59 to 25/10 01:00:00. Since there was no 25/10 00:00:00, the Dateformatter considers the date invalid. As you may be wondering, the same occurs for any other date when daylight saving time started at 00:00.

To know the start dates of daylight saving time you can check this article.

This can be solved using the property isLenient, that makes the Dateformatter use heuristics to infer the date to be converted.

dateFormatter.isLenient = true
  • Instead of using isLenient = true just configure the Dateformatter calendar dateFormatter.calendar = Calendar(identifier: .gregorian). Another important thing when this Parsing dates with fixed format is to use the dateFormatter.locale = Locale(identifier: "en_US_POSIX")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.