Aisenhein
Aisenhein

Reputation: 115

DateFormatter does NOT convert specific dates (Swift)

I have the below code on playground and app and DateFormatter are returning nil just for the date "1990-10-21":


let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd"

let date1 = dateFormatter.date(from: "1990-10-20") // "Oct 20, 1990 at 12:00 AM"
let date2 = dateFormatter.date(from: "1990-10-21") // nil
let date3 = dateFormatter.date(from: "1990-10-22") // "Oct 22, 1990 at 12:00 AM"

Testing with 1989, 2021... works fine...

Does anyone knows why or something about this? is it a bug?

Upvotes: 1

Views: 89

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236305

There are three issues with your code. First YYYY is for YearForWeekOfYear. What you need is yyyy. Second you are not passing the time. Note that not all days starts at 12:00am (daylight savings transition dates). You can prevent the date formatter returning nil by setting its calendar or passing a valid time (12pm) along with the date. Third you should always set the locale to "en_US_POSIX" when using a fixed date format:


let dateFormatter = DateFormatter()
dateFormatter.calendar = .current
dateFormatter.locale = .init(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd"

let date1 = dateFormatter.date(from: "1990-10-20") // "Oct 20, 1990 at 12:00 AM"
let date2 = dateFormatter.date(from: "1990-10-21") // "Oct 21, 1990 at 1:00 AM"
let date3 = dateFormatter.date(from: "1990-10-22") // "Oct 22, 1990 at 12:00 AM"

Upvotes: 3

Related Questions