I can get the offset seconds from GMT with this: TimeZone.current.secondsFromGMT()
.
However, how do I get the format as ±hh:mm
?
Definition and Usage. getTimezoneOffset() returns the difference between UTC time and local time. getTimezoneOffset() returns the difference in minutes. For example, if your time zone is GMT+2, -120 will be returned.
Current time: 14:07:10 UTC. UTC is replaced with Z that is the zero UTC offset. UTC time in ISO-8601 is 14:07:10Z.
The UTC offset is the difference in hours and minutes between Coordinated Universal Time (UTC) and local solar time, at a particular place. This difference is expressed with respect to UTC and is generally shown in the format ±[hh]:[mm], ±[hh][mm], or ±[hh].
The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss. sssZ , respectively). The timezone is always zero UTC offset, as denoted by the suffix Z .
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.
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