6

how can I get the GMT offset in javascript of the client?

new Date().getTimezoneOffset(); returns the difference from UTC. Is there a way I can calculate the GMT offset from that?

By GMT offset, I mean as in -5 for eastern standard time.

9
  • 1
    you can't unless you convert UTC to GMT. Commented Jun 30, 2014 at 23:26
  • @DanielA.White How do I do that? In javascript? Commented Jun 30, 2014 at 23:27
  • 1
    yea - theres libraries out there. Commented Jun 30, 2014 at 23:27
  • 4
    This question appears to be off-topic because UTC is GMT. Commented Jun 30, 2014 at 23:33
  • 2
    I don't agree with closing the question. The OP is asking how to convert an ECMAScript time zone offset to an ISO 8601 format offset from UTC. Far better to explain the difference between UTC and GMT and then answer the question (UTC is a time standard, GMT is a timezone, they both represent the same time but are different things). Commented Mar 17, 2016 at 22:46

1 Answer 1

24

new Date().getTimezoneOffset(); returns the difference from UTC. Is there a way I can calculate the GMT offset from that?

The timezone offset is the difference from GMT in minutes (see ECMA-262 §15.9.5.26). The sign is the reverse of ISO 8601, but it's easily converted to hours and minutes with a more standard sign:

function getTimezoneOffset() {
  function z(n){return (n<10? '0' : '') + n}
  var offset = new Date().getTimezoneOffset();
  var sign = offset < 0? '+' : '-';
  offset = Math.abs(offset);
  return sign + z(offset/60 | 0) + z(offset%60);
}

getTimezoneOffset() // +0800 for UTC/GMT + 8hrs

If you want to determine the IANA timezone designation, you can try pellepim jstimezonedetect, however it works by guessing based on the offset for two dates and may not be correct.

Sign up to request clarification or add additional context in comments.

6 Comments

Note, depending on usage, one may want to include a colon character (`:') between the hour and minute components of the offset. Easily done on the last line of the function.
does this handle cases like xx:30?
Yes. The string returned includes the sign, hours and minutes.
I don't understand the purpose of the bitwise OR operator here: z(offset/60 | 0). Isn't offset/60 | 0 always going to evaluate to offset/60?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.