Does it make sense to use locale and dateFormat together for NSDateFormatter?

Viewed 46

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

1 Answers

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.

Related