Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from UTC to local time in moment.js?

Tags:

momentjs

I have a simple use case but I cannot figure out how to convert from GMT/UTC to local time in moment.js.

Example:

var gmtDateTime = moment.utc("2015-10-24 20:00", "YYYY-MM-DD HH").format('YYYY-MMM-DD h:mm A');

console.log(gmtDateTime) emits 2015-Oct-24 8:00 PM, which is correct. Now I simply want to convert this to my local time, which happens to be Mountain Daylight Time. So the correct converted date would be 2015-Oct-24 2:00 PM, because I am 6 hours earlier than GMT/UTC.

How can this be done simply with moment.js?

like image 363
HerrimanCoder Avatar asked Oct 24 '15 17:10

HerrimanCoder


People also ask

How do you convert UTC to local time?

Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.).

Does moment convert to local time?

To convert UTC time to Local you have to use moment. local() .

How do you use UTC in moments?

utc() will be in UTC mode, and any moment created with moment() will not. To switch from UTC to local time, you can use moment#utc or moment#local.

What is moment tz ()?

For example, if you parse the string '2020/01/02' and then call the moment#tz() method, you're telling moment to parse the string in the locale time, and then convert the date to a given IANA timezone.


1 Answers

Try moment().local().

Example:

var gmtDateTime = moment.utc("2015-10-24 20:00", "YYYY-MM-DD HH")
var local = gmtDateTime.local().format('YYYY-MMM-DD h:mm A');
like image 50
Antti Kuosmanen Avatar answered Oct 06 '22 23:10

Antti Kuosmanen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!