Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get timezone offset between UTC and iPhone - Swift 4.2?

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()
        }
    }
})

Result

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 ?

like image 389
code-8 Avatar asked Feb 25 '19 22:02

code-8


2 Answers

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.

like image 57
Leo Dabus Avatar answered Oct 09 '22 21:10

Leo Dabus


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

like image 30
FullMetalFist Avatar answered Oct 09 '22 21:10

FullMetalFist