【问题标题】:iOS Get Time Zone String Without DST OffsetiOS获取没有DST偏移的时区字符串
【发布时间】:2019-11-07 04:46:30
【问题描述】:

我正在寻找一个时区列表,但是当我尝试生成时区时,我得到了添加到它的 DST 偏移量。但我想要标准时间,而不是带有 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)
    }

【问题讨论】:

    标签: ios swift date


    【解决方案1】:

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

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

    它会正确设置当前时间。

    【讨论】:

    • 我想要标准时间,即不添加 DST 偏移量,无论我当前所在的时区如何。
    • 这样就没有夏令时偏移
    猜你喜欢
    • 2016-12-07
    • 1970-01-01
    • 2015-05-18
    • 2020-04-08
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2011-08-04
    相关资源
    最近更新 更多