如何获得 UTC 和 iPhone - Swift 4.2 之间的时区偏移量?
How to get timezone offset between UTC and iPhone - Swift 4.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()
}
}
})
结果
如果我这样做
print(tzOffset)
我得到了
-0500
应该是 -5
因为我的当前时区是 America/Montreal
吗?
有人可以给我提示吗?
应该是-0500
.
它有 4 位而不是 1 位的原因是因为它采用 24 小时格式,并且某些时区是从 UTC 半小时开始计算的
您可以获取当前时区,获取 GMT 的秒数并将其除以 3600。
TimeZone.current.secondsFromGMT() / 3600 // -3 hs America/Sao_Paulo (current) Brazil
如果您需要更精确的精度,例如小数小时,只需在除法之前将其转换为双精度即可。
我在 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
吗?
有人可以给我提示吗?
应该是-0500
.
它有 4 位而不是 1 位的原因是因为它采用 24 小时格式,并且某些时区是从 UTC 半小时开始计算的
您可以获取当前时区,获取 GMT 的秒数并将其除以 3600。
TimeZone.current.secondsFromGMT() / 3600 // -3 hs America/Sao_Paulo (current) Brazil
如果您需要更精确的精度,例如小数小时,只需在除法之前将其转换为双精度即可。