Moment Js UTC to Local Time

brian Scroggins picture brian Scroggins · Sep 12, 2015 · Viewed 201.4k times · Source

I'm trying to convert UTC time to the local time. I've been following this example from this link: http://jsfiddle.net/FLhpq/4/light/. I can't seem to get the right local output. For example, if its 10: 30 am in here, instead of getting 10:30 ill get 15: 30. Here is my code:

var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');

var localTime  = moment.utc(date).toDate();

localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');

console.log("moment: " + localTime);

No matter what I do the time always comes out at UTC time. I live in Houston so I know timezone is the issue. I've followed the code in the link but can seem to get the local time. What am I doing wrong?

Answer

axon picture axon · Sep 12, 2015

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

For more info see docs

Example:

var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');

console.log(date); // 2015-09-13 03:39:27

var stillUtc = moment.utc(date).toDate();
var local = moment(stillUtc).local().format('YYYY-MM-DD HH:mm:ss');

console.log(local); // 2015-09-13 09:39:27

Demo:

var date = moment.utc().format();
console.log(date, "- now in UTC"); 

var local = moment.utc(date).local().format();
console.log(local, "- UTC now to local"); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>