Search code examples
swiftnsdateformatter

setLocalizedDateFormatFromTemplate removes -


I'm not sure why but DateFormatter seems to remove '-' when using localizedDateFormats and replaces it with a comma.

It doesn't seem to be a part of the unicode standard to remove the - field and turn it into a comma. I also tried surrounding the - with ''. I'm trying to use setLocalizedDateFormatFromTemplate in order to handle localization, so I can't just use use .dateFormat (which does solve it)

let dateHyphenFormatter = DateFormatter()
dateHyphenFormatter.setLocalizedDateFormatFromTemplate("LLL d YYYY ‐ j:mm a")
print(dateHyphenFormatter.string(from: Date())) // Jun 29, 2017, 1:57 PM

Solution

  • setLocalizedDateFormatFromTemplate is supposed to be used just with a set of format specifiers. The returned format reflects how those fields should appear in the given locale. So the order of the fields and any punctuation is determined for you. The order of the specifiers and any punctuation you put in the template are ignored. And in some cases, the actual format specifiers will be changed to better match the standards of the locale.

    You'll get the same format with the following templates:

    LLLdyyyyjmma
    yyyyLLLdjmma
    

    and any other order of those specifiers and any other (ignored) punctuation you put in there.

    FYI - do not use YYYY. You want yyyy.

    Here's some test code that demonstrates how each locale uses your template:

    for localeId in Locale.availableIdentifiers.sorted() {
        let locale = Locale(identifier: localeId)
        if let format = DateFormatter.dateFormat(fromTemplate: "yyyyLLLdjmma", options: 0, locale: locale) {
            print("\(localeId) - \(format)")
        }
    }
    

    Note that this code crashes for some reason with Xcode 9 beta 2 so be sure to test this with Xcode 8.