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

kyo*_*kyo 6 timezone timezone-offset swift

我使用的是Swift 4.2。我正在努力获取 UTC 和 iPhone 上的时间之间的偏移时间。


我有这个代码

extension TimeZone {
    func offsetFromGMT() -> String
    {
        let localTimeZoneFormatter = DateFormatter()
        localTimeZoneFormatter.timeZone = self
        localTimeZoneFormatter.dateFormat = "Z"
        return localTimeZoneFormatter.string(from: Date())
    }
}
Run Code Online (Sandbox Code Playgroud)
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()
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

结果

如果我做

print(tzOffset)
Run Code Online (Sandbox Code Playgroud)

我有

-0500
Run Code Online (Sandbox Code Playgroud)

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

有人可以给我提示吗?

Leo*_*bus 6

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

TimeZone.current.secondsFromGMT() / 3600    // -3 hs America/Sao_Paulo (current) Brazil
Run Code Online (Sandbox Code Playgroud)

如果您需要更精确的精度(例如小时的分数),只需在除法之前将其转换为双精度即可。