Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MomentJS set timezone without changing time

Tags:

I'm trying to set the timezone for a date in moment.js without changing the time value

I get a date in utc:

date.toString() //Sun Sep 27 2015 00:00:00 GMT+0000

and I need to set the time zone without changing the time.

Sun Sep 27 2015 00:00:00 GMT-0500

if I use date.utcOffset(moment().utcOffset()) it adds the offset:

date.toString() //Sat Sep 26 2015 19:00:00 GMT-0500

I could do

date = moment(date.format("YYYYMMDDHHmmssSSSS"), "YYYYMMDDHHmmssSSSS")

but that seems like an inefficient way to do it.

Is there any method that will just change the timezone without changing the time?

like image 985
Tony Brix Avatar asked Oct 29 '15 18:10

Tony Brix


People also ask

How do you pass timezone in Momentjs?

To change the default time zone, use moment. tz. setDefault with a valid time zone.

Is Momentjs deprecated?

moment().zone is deprecated, use moment().utcOffset instead.

How do I get timezone offset?

The JavaScript getTimezoneOffset() method is used to find the timezone offset. It returns the timezone difference in minutes, between the UTC and the current local time. If the returned value is positive, local timezone is behind the UTC and if it is negative, the local timezone if ahead of UTC.

How do I get the current time in Momentjs?

What is the appropriate way to get the current time on the machine? var CurrentDate = moment(). format();


2 Answers

At the time of writing this (Moment 2.22), you could go from local to UTC with someLocalMomentVariable.utc(true) then back from UTC to local with someUtcMomentVariable.local(true).

like image 187
Grinn Avatar answered Sep 21 '22 07:09

Grinn


If you are using moment.js use utcOffset with true as second parameter eg: date2 = moment(date1).utcOffset('+0400', true)

Of If you are using moment-timezone, you can use tz function on moment object with second parameter as true eg: date1 = moment(date1).tz('Asia/Kolkata', true)

like image 42
Inayath Ebrahim Avatar answered Sep 20 '22 07:09

Inayath Ebrahim