I'm on Swift 4.2. I'm struggling trying to get the offset time between UTC and the one from my iPhone.
I have this code
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()
}
}
})
If I do
print(tzOffset)
I got
-0500
Should it be -5
since my currentTimeZone is America/Montreal
?
Can someone please give me a hints ?
You can get the current timezone, get the number of seconds from GMT and divide it by 3600.
TimeZone.current.secondsFromGMT() / 3600 // -3 hs America/Sao_Paulo (current) Brazil
If you need more precision like fraction of hour as well just convert it to double before dividing it.
it should be -0500
.
From the Wikipedia page
The reason why it has 4 digits instead of one is because it is in a 24 hour format, and some time zones are measured in a half-hour distance from UTC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With