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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With