Swift - How do I get an NSTimeZone to give me "Pacific Standard Time" or "Mountain Time" etc?

538 Views Asked by At

The API I am using gives me names like "America/Vancouver". I use this to construct an NSTimeZone and get the the abbreviation, but it's "UTC-7" when I want "Pacific Daylight Time" or "PDT".

How can I get into the zone? And not the danger zone.

1

There are 1 best solutions below

0
Leo Dabus On BEST ANSWER

You can use TimeZone method localizedName(for: locale:) to display your timezone name localized. You just need to pass a name style daylight savings or standard. If you need the abbreviation just pass short daylight savings or short standard as I have shown in this post:


extension TimeZone {
    static let vancouver = TimeZone(identifier: "America/Vancouver")!
    func localizedName(for date: Date = Date()) -> String { localizedName(for: isDaylightSavingTime(for: date) ? .daylightSaving : .standard, locale: .current) ?? "" }
    func localizedNameShort(for date: Date = Date()) -> String { localizedName(for: isDaylightSavingTime(for: date) ? .shortDaylightSaving : .shortStandard, locale: .current) ?? "" }
}

Usage:

TimeZone.vancouver.localizedName()        // "Pacific Daylight Time"
TimeZone.vancouver.localizedNameShort()   // "PDT"