我正在寻找一个时区列表,但当尝试生成时,我会将DST偏移量添加到其中。但我要的是标准时间,而不是夏令时。
这是我正在使用的代码。对于丹麦,我得到的是GMT+2而不是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)
    }

最佳答案

请尝试这样设置格式化程序的时区

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

它将正确设置当前时间。

关于ios - iOS获取没有DST偏移量的时区字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56752467/

10-16 18:58