Get timezone from users browser using moment(timezone).js
Asked Answered
E

9

121

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?

Ethe answered 3/11, 2016 at 12:29 Comment(1)
Now since moment is discontinued. Check https://mcmap.net/q/21145/-getting-the-client-39-s-time-zone-and-offset-in-javascript for super simple one liner without any libraries.Jareb
Q
27
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.

Quartered answered 3/11, 2016 at 12:47 Comment(5)
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 wikiSocket
@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).Granule
This doesn't work in Firefox, new Date() creates a date object in UTC timezone, so it is pointless to getTimezoneOffset() on itGladisgladney
So how do we play around with it with moment?Defect
@KrzysztofKrasoń I just tried this and it does in fact work in both Chrome and Firefox (version 104.0.2).Westleigh
S
306

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.

Socket answered 3/11, 2016 at 16:54 Comment(8)
See also this answer and this answer.Socket
Great answer - Upvoted! Also please use momet-timezone version 0.5.4 or higher... please follow this thread for further explanations github.com/moment/moment-timezone/issues/324Sweepstakes
+1. Make sure your using moment with date to utilize the tz hook. 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');Blab
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.Granule
Is the timezone taken from the browser or the device?Callicrates
@bubble - It's taken from whichever environment the code is executing in.Socket
from the wiki tag: 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? thanksEnunciation
@Enunciation - 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)Socket
Q
27
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.

Quartered answered 3/11, 2016 at 12:47 Comment(5)
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 wikiSocket
@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).Granule
This doesn't work in Firefox, new Date() creates a date object in UTC timezone, so it is pointless to getTimezoneOffset() on itGladisgladney
So how do we play around with it with moment?Defect
@KrzysztofKrasoń I just tried this and it does in fact work in both Chrome and Firefox (version 104.0.2).Westleigh
M
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()
}
Metonymy answered 26/11, 2017 at 1:22 Comment(2)
The function is actually utcOffset(), not offsetUtc() :)Gimmal
@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).Metonymy
V
7

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
Viyella answered 28/2, 2019 at 13:24 Comment(1)
TypeError: time.tz is not a function const time = moment().format('YYYY/MM/DD HH:mm:ss'); time.tz()Whomever
A
2

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

Arteritis answered 2/4, 2021 at 13:45 Comment(0)
G
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

Gradual answered 17/5, 2018 at 12:35 Comment(1)
You cannot get client timezone that way.Geldens
M
0
moment().format("MMM DD YYYY")

This will provide the time zone of the application, not the system.

Marlanamarlane answered 18/11, 2023 at 19:13 Comment(0)
A
-1

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.

Apprehensive answered 8/2, 2022 at 8:29 Comment(0)
M
-1

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

moment().utcOffset(0, true).format()
Mistaken answered 21/6, 2022 at 6:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.