Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

569
Views
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 ?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!