Search code examples
iosswiftdatetimedate-parsingdateformatter

How to convert string to date correctly?


Why does dateFormatter return the correct date from an invalid format string?

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd"

let date = dateFormatter.date(from: "2020/////07////////10") //"Jul 10, 2020 at 12:00 AM"

Solution

  • I will say more - it also works unexpectedly

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    
    let dotDate = dateFormatter.date(from: "2020....07...10") // Optional(2020-07-09 21:00:00 +0000)
    let commaDate = dateFormatter.date(from: "2020,,,,07,,,,10") // Optional(2020-07-09 21:00:00 +0000)
    

    My version is probably the issue in internal implementation on Apple side and comparison with the ASCII code table, where the codes of these characters (,,-,.,/) are in order (from 44 to 47)