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
Related videos on Youtube
Author by
TruMan1
Updated on September 14, 2022Comments
-
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
?-
rmaddy about 7 yearsPossible duplicate of Convert Seconds Integer To HH:MM, iPhone
-
-
Martin R almost 7 years@Himanshujamnani:
TimeZone.current.secondsFromGMT()
is the UTC offset. -
Bhanuteja over 4 yearswhy are you hard coding "+"?. If it is "-01:00", it will print the same?
-
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 about 2 yearsPerfect solution, It's working for me.
-
Geoff H about 2 years5 Zs! 'Attaboy!