3

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"
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • May be this helps: https://stackoverflow.com/questions/26840499/nsdateformatter-still-parsing-instead-having-incorrect-format – Kishan Bhatiya Jan 24 '20 at 14:01

3 Answers3

3

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)

Vadim Nikolaev
  • 2,132
  • 17
  • 34
0

This is probably a part of their algorithm.

If you want the formatter to return nil in this case you can change the dateFormat to:

dateFormatter.dateFormat = "yyyy/MM/dd"

Results

let date = dateFormatter.date(from: "2020/////07////////10") // nil 
let date2 = dateFormatter.date(from: "2020/07/10") // Jul 10, 2020 at 12:00 AM"
let date3 = dateFormatter.date(from: "2020.07.10") // Jul 10, 2020 at 12:00 AM"
Tal Cohen
  • 1,308
  • 10
  • 20
0

I did run your code and it gives nil

Whereas if I enter correct date format then I receive the output

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: "2020-7-10")
print(date) // Optional(2020-07-10 00:00:00 +0000)
Keshu R.
  • 5,045
  • 1
  • 18
  • 38