如何获得UTC和iPhone之间的时区偏移 - Swift 4.2?

问题描述 投票:2回答:2

我在Swift 4.2上。我正在努力试图获得UTC与iPhone之间的偏移时间。


我有这个代码

extension TimeZone {
    func offsetFromGMT() -> String
    {
        let localTimeZoneFormatter = DateFormatter()
        localTimeZoneFormatter.timeZone = self
        localTimeZoneFormatter.dateFormat = "Z"
        return localTimeZoneFormatter.string(from: Date())
    }
}

func getCurrentTimeZone() -> String{
    return String (TimeZone.current.identifier)
}


var tzOffset = ""
let currentTimeZone = getCurrentTimeZone()
TimeZone.knownTimeZoneIdentifiers.forEach({ timeZoneIdentifier in
    if let timezone = TimeZone(identifier: timeZoneIdentifier)
    {
        //print("\(timezone.identifier) \(timezone.offsetFromGMT())")

        if(timezone.identifier == currentTimeZone){
            tzOffset = timezone.offsetFromGMT()
        }
    }
})

Result

如果我做

print(tzOffset)

我有

-0500

它应该是-5,因为我的currentTimeZone是America/Montreal

有人可以给我一些提示吗?

swift timezone timezone-offset
2个回答
1
投票

您可以获取当前时区,从GMT获取秒数并将其除以3600。

TimeZone.current.secondsFromGMT() / 3600    // -3 hs America/Sao_Paulo (current) Brazil

1
投票

它应该是-0500

From the Wikipedia page

它有4个数字而不是1个数字的原因是因为它是24小时格式,而某些时区是在距离UTC的半小时距离内测量的

© www.soinside.com 2019 - 2024. All rights reserved.