2

So does it make sense? I think dateFormat itself specify exactly the output, isn't it?

János
  • 32,867
  • 38
  • 193
  • 353

1 Answers1

2

If you need to parse a date you can use both at the same time:

let formater = DateFormatter()
let enDateString = "2019, 16 January"
formater.locale = Locale(identifier: "en_US")
formater.dateFormat = "yyyy, dd MMMM"

let enDate = formater.date(from: enDateString)
print(enDate) // display: Optional(2019-01-16 00:00:00 +0000)

let frDateString = "16 janvier 2019"
formater.locale = Locale(identifier: "fr_FR")
formater.dateFormat = "dd MMMM yyyy"

let frDate = formater.date(from: frDateString)
print(frDate) // display: Optional(2019-01-16 00:00:00 +0000)

Here the MMMM pattern in the dateFormat allows you to parse the month in plain text in the targeted locale.

Yannick Loriot
  • 7,107
  • 2
  • 33
  • 56
  • You should never use `dateFormat` when showing a date to a user, regardless of locale. Use `dateStyle` and `timeStyle`. Setting a locale and using `dateFormat` is largely a contradiction. Only used `dateFormat` when you need to parse a fixed format date string or you need to generate a fixed format string to send to a server or something similar. – rmaddy Jan 16 '19 at 23:01
  • Do you know, does it make sense to use for this string `local`? There is no month in plain text or similar here, only digits: `dd/MM/yyyy HH:mm` – János Jan 17 '19 at 20:58
  • @János When you use a fixed format like that, you need to use the special locale of `en_US_POSIX`. – rmaddy Jan 17 '19 at 21:00
  • Hi @rmaddy! Why? – János Jan 17 '19 at 21:55
  • 1
    @János See https://stackoverflow.com/questions/6613110/what-is-the-best-way-to-deal-with-the-nsdateformatter-locale-feechur?rq=1 – rmaddy Jan 17 '19 at 21:57