Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment Js UTC to Local Time

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?

like image 497
brian Scroggins Avatar asked Sep 12 '15 15:09

brian Scroggins


People also ask

How do you convert UTC time to local time in node js?

Use the Date() constructor to convert UTC to local time, e.g. new Date(utcDateStr) . Passing a date and time string in ISO 8601 format to the Date() constructor converts the UTC date and time to local time. Copied!

Does MomentJS use local timezone?

The main moment. js library has full functionality for working with UTC and the local time zone.


2 Answers

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>
like image 194
axon Avatar answered Sep 16 '22 20:09

axon


Try this:

let utcTime = "2017-02-02 08:00:13";  var local_date= moment.utc(utcTime ).local().format('YYYY-MM-DD HH:mm:ss'); 
like image 42
JAMZAD Avatar answered Sep 18 '22 20:09

JAMZAD