Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateFormatter localizedString - only day and month, without year [duplicate]

Is it possible to get localized string from date only with month and day?

let localizedDate = DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .none)

This prints Sept 15, 2017 or 15 Sep 2017.

I would like to honor user's date format and not display the year, only month and day. I mean Sept 15 or 15 Sep. Is it possible?

like image 375
Bartłomiej Semańczyk Avatar asked Sep 09 '17 12:09

Bartłomiej Semańczyk


1 Answers

You can create a formate for just the day and the month and use that to create a format template. The DateFormatter will then localise it. As an example from an (Xcode9) playground:

let date = Date()
let customFormat = "ddMMMM"

let gbLocale = Locale(identifier: "en_GB")
let ukFormat = DateFormatter.dateFormat(fromTemplate: customFormat, options: 0, locale: gbLocale)
let usLocale = Locale(identifier: "en_US")
let usFormat = DateFormatter.dateFormat(fromTemplate: customFormat, options: 0, locale: usLocale)

let formatter = DateFormatter()
formatter.dateFormat = ukFormat
formatter.string(from: date) // -> "09 September"

formatter.dateFormat = usFormat
formatter.string(from: date) // -> "September 09"

If you pass in Locale.current to the templateFormatter instead of the example ones I created, then you will get the localised versions of your template.

Your question asks about short month format so you can replace "MMMM" in the custom format with "MMM" to get the shortened month name displayed instead of the full one. and a "d" instead of "dd" to not have leading "0" in the date. I'm sure you know what I mean.

like image 106
Abizern Avatar answered Nov 13 '22 17:11

Abizern