gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:07:30 25 4
gpt4 key购买 nike

我正在使用 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()
}
}
})

结果

如果我这样做

print(tzOffset)

我得到了

-0500

它应该是 -5 因为我的当前时区是 America/Montreal 吗?

有人可以给我提示吗?

最佳答案

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

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

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

关于swift - 如何获得 UTC 和 iPhone 之间的时区偏移 - Swift 4.2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54875915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com