Here's some modern Swift code based on @eskimo's recommended approach. My requirement was to localize a "month/day" string, e.g. Apr 28, so it would appear as "4/28" in the U.S., but reformatted as "28/4" or similar in other locales.
The +dateFormat(fromTemplate:options:locale) function seems to be smart enough to flip the "M/d" around to match the locale.
@eskimo, does this look like a valid implementation?
import Foundation
let now = Date()
for localeIdentifier in Locale.availableIdentifiers {
let locale = Locale(identifier: localeIdentifier)
let forcedLocale = gregorianForcedLocale(using: locale)
let dateFormat = DateFormatter.dateFormat(fromTemplate: "M/d", options: 0, locale: forcedLocale)!
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .gregorian)
formatter.dateFormat = dateFormat
let dateString = formatter.string(from: now)
print(localeIdentifier + ", " + dateFormat + ", " + dateString)
}
func gregorianForcedLocale(using locale: Locale) - Locale {
let localeIdentifier = locale.identifier
var components = Locale.components(fromIdentifier: localeIdentifier)
components["calendar"] = "gregorian"
let customLocaleIdentifier = Locale.identifier(fromComponents: components)
let customLocale = Locale(identifier: customLocaleIdentifier)
return customLocale
}
Topic:
Accessibility & Inclusion
SubTopic:
General
Tags: