The first April dates of the 80s could not be analyzed in iOS 10.0

I found that the DateFormatter method date(from:)cannot parse a couple of specific dates. The method returns nilfor April 1, 1981-1984. Is this a mistake of the Foundation? What can we do to parse such dates?

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

+4
source share
1 answer

This problem arises if daylight saving time begins at exactly midnight, as it was in Moscow in 1981-1984 (see, for example, Clock Changes in Moscow, Russia (Moscow) ).

It was also observed in

, 1 1984 , , "1984-04-01 00:00" :

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

, "":

dFmt.isLenient = true

:

dFmt.isLenient = true
if let date = dFmt.date(from: "1984-04-01") {
    dFmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
    print(dFmt.string(from: date)) 
}
// 1984-04-01 01:00:00

rob mayoff, , . rob Objective-C Swift:

let noon = DateComponents(calendar: dFmt.calendar, timeZone: dFmt.timeZone,
               year: 2001, month: 1, day: 1, hour: 12, minute: 0, second: 0)
dFmt.defaultDate = noon.date
if let date = dFmt.date(from: "1984-04-01") {
    dFmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
    print(dFmt.string(from: date)) 
}
// 1984-04-01 12:00:00
+14

Source: https://habr.com/ru/post/1659059/


All Articles