Search code examples
swiftdatetime-format

Get time formatter string for AM / PM without using time


Is there a way to get AM / PM localized string from time formatter without using any given time?

Something like:

let locale = Locale(identifier: "en-us")
        
let formatter = DateFormatter()
formatter.locale = locale
formatter.dateFormat = "a"

and somehow print "am" and "pm" variant.


Solution

  • You can get it from Calendar, using the amSymbol and pmSymbol properties.

    var calendar = Calendar.current
    // set the locale if you want am/pm for a non-current locale
    // calendar.locale = someLocale
    let am = calendar.amSymbol
    let pm = calendar.pmSymbol