Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get timezone offset as ±hh:mm?

Tags:

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

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

like image 826
TruMan1 Avatar asked Feb 14 '17 20:02

TruMan1


People also ask

How do I get a time zone offset?

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.

What is my UTC time zone offset?

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.

How do you write time with UTC offset?

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].

How do I find the timezone in an ISO date?

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 .


1 Answers

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.

like image 95
Martin R Avatar answered Nov 06 '22 02:11

Martin R