Search code examples
iosswiftdatensdateformatterdateformatter

iOS Date Formatting without year, with correct localization


Do you know how I could have the following date string Jun 28 on iOS?

  • Jun 28 in English
  • 28 juin in French
  • etc

I want basically short month, day, without year. (in the localized order, so day, month in French for instance)

I tried the following:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd"
let dateStr = dateFormatter.string(from: Date())
print(dateStr) // --> Jun 28

It works in English but not in other languages.

For instance if you set
dateFormatter.locale = Locale(identifier: "fr”)
It should output 28 juin but it returns juin 28.

I also tried to use:

let date = Date()
let customFormat = "MMM dd"
let frLocale = Locale(identifier: "fr_FR")
let frFormat = DateFormatter.dateFormat(fromTemplate: customFormat, options: 0, locale: frLocale)
let formatter = DateFormatter()
formatter.dateFormat = frFormat
let dateStr = formatter.string(from: date)
print(dateStr) // -> 28 Jun

^__ the order is correct but the month is in English.

What is the closest is:

let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .none
dateFormatter.dateStyle = .medium
let dateStr = dateFormatter.string(from: Date())
print(dateStr) // --> Jun 28, 2020

^__ but I don't want the year.


Solution

  • I believe this part of the documentation is the key (I mean if I was just to re-set the locale on the formatter without setting again the template, I would get what you describe in the first case):

    func setLocalizedDateFormatFromTemplate(String)

    Important: You should call this method only after setting the locale of the receiver.

    and sure enough, when you do this, you get correct formatting:

    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US")
    dateFormatter.setLocalizedDateFormatFromTemplate("MMM dd")
    print(dateFormatter.string(from: Date())) // --> Jun 28
    
    dateFormatter.locale = Locale(identifier: "fr_FR")
    dateFormatter.setLocalizedDateFormatFromTemplate("MMM dd")
    print(dateFormatter.string(from: Date())) // --> 28 juin
    

    By the way, there is a really good session about formatters in WWDC'20