iOS Get Time Zone String Without DST Offset

Viewed 162

I am looking for a list of timezones but when try to generate that I get the DST offset added to it. But I want the standard time, not the one with DST. Here is the code I am using. For Denmark, I am getting GMT+2 instead of GMT+1

    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .long
    dateFormatter.timeStyle = .long
    dateFormatter.dateFormat = "ZZZZ"

    let list = TimeZone.knownTimeZoneIdentifiers
    for (i, city) in list.enumerated() {
        let timezone = TimeZone(identifier: city)
        dateFormatter.timeZone = timezone

        var isSupportDST = false
        if timezone?.nextDaylightSavingTimeTransition != nil {
            isSupportDST = true
        }

        let date = Date()
        var timezoneString = dateFormatter.string(from: date)

        if timezoneString.count > 3 {
            timezoneString.insert(" ", at: timezoneString.index(timezoneString.startIndex, offsetBy: 3))
        }
        if timezoneString.count > 5 {
            timezoneString.insert(" ", at: timezoneString.index(timezoneString.startIndex, offsetBy: 5))
        }

        var formattedCityName = city
        formattedCityName = city.replacingOccurrences(of: "_", with: " ")

        var dstoffset = 0 as TimeInterval
        if let offset = timezone?.daylightSavingTimeOffset(){
            dstoffset = offset
        }

        let cityWithTimezone = CityWithTimeZone(city: formattedCityName, timeZoneString: timezoneString, timeZoneInSeconds: timezone?.secondsFromGMT() ?? 0, dstOffset: dstoffset, isDSTSupport: isSupportDST)
        cityList.insert(cityWithTimezone, at:i)
    }
1 Answers

Please try to set the timezone of the formatter like this

let timezone = TimeZone(identifier: city)
dateFormatter.timeZone = TimeZone(secondsFromGMT: TimeZone.current.secondsFromGMT())

It will set the current time properly.

Related