114

What is the best way to get client's timezone and convert it to some other timezone when using moment.js and moment-timezone.js

I want to find out what is clients timezone and later convert his date and time into some other timezone.

Does anybody has experience with this?

Dariusz Woźniak
  • 9,640
  • 6
  • 60
  • 73
nemo_87
  • 4,523
  • 16
  • 56
  • 102
  • Now since moment is discontinued. Check https://stackoverflow.com/a/34602679/4050261 for super simple one liner without any libraries. – Adarsh Madrecha Nov 13 '20 at 17:57

8 Answers8

299

When using moment.js, use:

var tz = moment.tz.guess();

It will return an IANA time zone identifier, such as America/Los_Angeles for the US Pacific time zone.

It is documented here.

Internally, it first tries to get the time zone from the browser using the following call:

Intl.DateTimeFormat().resolvedOptions().timeZone

If you are targeting only modern browsers that support this function, and you don't need Moment-Timezone for anything else, then you can just call that directly.

If Moment-Timezone doesn't get a valid result from that function, or if that function doesn't exist, then it will "guess" the time zone by testing several different dates and times against the Date object to see how it behaves. The guess is usually a good enough approximation, but not guaranteed to exactly match the time zone setting of the computer.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • See also [this answer](http://stackoverflow.com/a/16526897/634824) and [this answer](http://stackoverflow.com/a/18252251/634824). – Matt Johnson-Pint Nov 03 '16 at 16:58
  • 2
    Great answer - Upvoted! Also please use `momet-timezone` version **0.5.4** or higher... please follow this thread for further explanations https://github.com/moment/moment-timezone/issues/324 – ymz Sep 05 '17 at 09:48
  • 5
    +1. Make sure your using moment with date to utilize the tz hook. https://momentjs.com/timezone/docs/ to installed it with node.js use this command `npm install moment-timezone` then required it like this `window.moment = require('moment-timezone');` – Junior Nov 18 '17 at 21:42
  • It's really important that people know: this is the correct answer. The currently accepted answer gives you timezone OFFSET (a `+/-INT` value) , not the timezone (a string like "America/Los Angeles"). They are two totally different concepts. – dudewad Jan 15 '18 at 22:32
  • 2
    Is the timezone taken from the browser or the device? – MartaGalve Jun 20 '18 at 05:00
  • 3
    @bubble - It's taken from whichever environment the code is executing in. – Matt Johnson-Pint Jun 20 '18 at 15:30
  • from [the wiki tag](https://stackoverflow.com/tags/timezone/info): *One can determine the correct offset, given a time zone and a datetime. But one cannot determine the correct time zone given just an offset.*. then, can one determine the correct time zone given an offset AND a datetime? if yes, couldn't one determine the correct (current) time zone in a browser given the client's offset and current datetime? thanks – Scaramouche Apr 28 '20 at 18:55
  • 1
    @Scaramouche - That's not related to what's being asked here. Please don't chain on to old comments, but rather ask a new question. (short answer - no, you still cannot) – Matt Johnson-Pint Apr 28 '20 at 20:24
26
var timedifference = new Date().getTimezoneOffset();

This returns the difference from the clients timezone from UTC time. You can then play around with it as you like.

jogoe
  • 482
  • 6
  • 18
  • 62
    This returns the *current* time zone *offset*. Not the time zone. The offset can change, based on things like daylight saving time. See "Time Zone != Offset" in [the timezone tag wiki](http://stackoverflow.com/tags/timezone/info) – Matt Johnson-Pint Nov 03 '16 at 16:56
  • 11
    @MattJohnson's answer is the true answer to this question. Technically this answer is incorrect as it is offset-related, not timezone-related (different concepts). – dudewad Jan 15 '18 at 22:33
  • 1
    This doesn't work in Firefox, new Date() creates a date object in UTC timezone, so it is pointless to getTimezoneOffset() on it – Krzysztof Krasoń Apr 05 '18 at 09:08
  • So how do we play around with it with moment? – Raymond Chen Oct 04 '18 at 03:57
  • @KrzysztofKrasoń I just tried this and it does in fact work in both Chrome and Firefox (version 104.0.2). – Athlon Nov 09 '22 at 20:03
9

All current answers provide the offset differece at current time, not at a given date.

moment(date).utcOffset() returns the time difference in minutes between browser time and UTC at the date passed as argument (or today, if no date passed).

Here's a function to parse correct offset at the picked date:

function getUtcOffset(date) {
  return moment(date)
    .subtract(
      moment(date).utcOffset(), 
      'minutes')
    .utc()
}
tao
  • 82,996
  • 16
  • 114
  • 150
  • 1
    The function is actually `utcOffset()`, not `offsetUtc()` :) – Milkncookiez Nov 22 '18 at 09:09
  • 2
    @Milkncookiez, I updated the answer. Thank you. No idea how I inverted them (it might be a case of working both ways or being changed in some prior version - the probability of me posting something I haven't tested is close to `null`). – tao Nov 22 '18 at 10:01
6

Using Moment library, see their website -> https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/

i notice they also user their own library in their website, so you can have a try using the browser console before installing it

moment().tz(String);

The moment#tz mutator will change the time zone and update the offset.

moment("2013-11-18").tz("America/Toronto").format('Z'); // -05:00
moment("2013-11-18").tz("Europe/Berlin").format('Z');   // +01:00

This information is used consistently in other operations, like calculating the start of the day.

var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.format();                     // 2013-11-18T11:55:00-05:00
m.startOf("day").format();      // 2013-11-18T00:00:00-05:00
m.tz("Europe/Berlin").format(); // 2013-11-18T06:00:00+01:00
m.startOf("day").format();      // 2013-11-18T00:00:00+01:00

Without an argument, moment#tz returns:

    the time zone name assigned to the moment instance or
    undefined if a time zone has not been set.

var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.tz();  // America/Toronto
var m = moment.tz("2013-11-18 11:55");
m.tz() === undefined;  // true
Philippe
  • 495
  • 1
  • 7
  • 18
1

You can also get your wanted time using the following JS code:

new Date(`${post.data.created_at} GMT+0200`)

In this example, my received dates were in GMT+0200 timezone. Instead of it can be every single timezone. And the returned data will be the date in your timezone. Hope this will help anyone to save time

David
  • 1,365
  • 14
  • 23
1

if the user's timezone is all you wanted then

const localtz = moment.tz.guess() // returns user's timezone

Additionally if you wanted to use it then the best way to convert a timestamp to user's timezone is

const time = moment.tz(response.timestamp)
const localtz = moment.tz.guess() // user's timezone
const date = time.clone().tz(localtz) // convert time to user's timezone

here localtz is the user's timezone and using it we can convert the timestamp to user's local time

Nishith
  • 928
  • 9
  • 13
0

First, you can find out the clients time zone using the following

let zoneVal = moment().tz(Intl.DateTimeFormat().resolvedOptions().timeZone).format('Z')

it will return you the GMT zone format for example +5:30 (colombo/srilanka & Delhi/India) or +6:00(Dhaka Bangladesh) depending on the region you are in.

secondly, if you want to find out the time of a particular time zone , then do the following

moment.tz("Asia/Dhaka").format()

which will return you the time zone value in ISO format of Dhaka.

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
0

Using moment timezone you can get easily your local date-time

moment().utcOffset(0, true).format()
Mr.Developer
  • 489
  • 2
  • 8