Skip to content

Talk about the “j” format template #35

@Frizlab

Description

@Frizlab

This one is a weirdo, but very cool.
It is not available on a formatter’s dateFormat directly, instead it exists on the class method dateFormat(fromTemplate:, options:, locale:), and thus on the instance method setLocalizedDateFormatFromTemplate(_:).

Setting the template to j on a formatter will return the hour either in 24-hour time or am/pm depending on the locale.
An example

import Foundation
let formatter = DateFormatter()

formatter.locale = Locale(identifier: "fr")
formatter.setLocalizedDateFormatFromTemplate("j")
print(formatter.string(from: Date())) /* -> "19 h" */

/* Same example with a different locale */
formatter.locale = Locale(identifier: "en_US")
formatter.setLocalizedDateFormatFromTemplate("j") /* Must be set again after changing the locale. */
print(formatter.string(from: Date())) /* -> "7 PM" */

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions