supp-f supp-f - 1 month ago 6
Swift Question

1st april dates of 80s failed to parse in iOS 10.0

I found that DateFormatter

date(from:)
method can't parse a couple of specific dates. Method returns
nil
for the 1st april of 1981-1984 years. Is it a bug of Foundation? What can we do to perform parsing of such dates?

Xcode 8.0, iOS SDK 10.0. Here is a screenshot of a short playground example:
a screenshot of a short playground example

Answer

You are in a time zone where the daylight saving time started at midnight of April 1st of those years. For example, at midnight of April 1st 1984, the clocks were adjusted one hour forward, which means that the date "1984-04-01 00:00" does not exist in that timezone:

let dFmt = DateFormatter()
dFmt.dateFormat = "yyyy-MM-dd"
dFmt.timeZone = TimeZone(identifier: "Europe/Moscow")
print(dFmt.date(from: "1984-04-01")) // nil

As a solution, you can tell the date formatter to be "lenient":

dFmt.isLenient = true

and then it will return the first valid date on that day.

Comments