How to get timezone offset as ±hh:mm?

12,830

Solution 1

Some integer arithmetic to obtain the offset in hours and minutes:

let seconds = TimeZone.current.secondsFromGMT()

let hours = seconds/3600
let minutes = abs(seconds/60) % 60

Formatted printing:

let tz = String(format: "%+.2d:%.2d", hours, minutes)
print(tz) // "+01:00" 

%.2d prints an integer with (at least) two decimal digits (and leading zero if necessary). %+.2d is the same but with a leading + sign for non-negative numbers.

Solution 2

Here is extension for getting timezone offset Difference and as ±hh:mm (Swift 4 | Swift 5 Code)

extension TimeZone {

    func offsetFromUTC() -> String
    {
        let localTimeZoneFormatter = DateFormatter()
        localTimeZoneFormatter.timeZone = self
        localTimeZoneFormatter.dateFormat = "Z"
        return localTimeZoneFormatter.string(from: Date())
    }

    func offsetInHours() -> String
    {
    
        let hours = secondsFromGMT()/3600
        let minutes = abs(secondsFromGMT()/60) % 60
        let tz_hr = String(format: "%+.2d:%.2d", hours, minutes) // "+hh:mm"
        return tz_hr
    }
}

Use like this

print(TimeZone.current.offsetFromUTC()) // output is +0530
print(TimeZone.current.offsetInHours()) // output is "+05:30"

Solution 3

If you can use Date()

func getCurrentTimezone() -> String {
        let localTimeZoneFormatter = DateFormatter()
        localTimeZoneFormatter.dateFormat = "ZZZZZ"
        return localTimeZoneFormatter.string(from: Date())
    }

Will return "+01:00" format

Share:
12,830

Related videos on Youtube

TruMan1
Author by

TruMan1

Updated on September 14, 2022

Comments

  • TruMan1
    TruMan1 over 1 year

    I can get the offset seconds from GMT with this: TimeZone.current.secondsFromGMT().

    However, how do I get the format as ±hh:mm?

  • Martin R
    Martin R almost 7 years
    @Himanshujamnani: TimeZone.current.secondsFromGMT() is the UTC offset.
  • Bhanuteja
    Bhanuteja over 4 years
    why are you hard coding "+"?. If it is "-01:00", it will print the same?
  • Martin R
    Martin R over 4 years
    @ammateja: + in the %+.2d format prepends a plus sign only to positive numbers (and zero). Negative numbers are still printed with a leading minus sign.
  • Jaywant Khedkar
    Jaywant Khedkar about 2 years
    Perfect solution, It's working for me.
  • Geoff H
    Geoff H about 2 years
    5 Zs! 'Attaboy!