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?
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!
The main moment. js library has full functionality for working with UTC and the local time zone.
To convert UTC time to Local you have to use moment.local()
.
For more info see docs
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
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>
Try this:
let utcTime = "2017-02-02 08:00:13"; var local_date= moment.utc(utcTime ).local().format('YYYY-MM-DD HH:mm:ss');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With