问题描述
我正在尝试将UTC时间转换为当地时间。我一直在这个链接中关注这个例子:。我似乎无法获得正确的本地输出。例如,如果它在上午10点30分,而不是得到10:30生病得到15:30。这是我的代码:
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);
无论我做什么,时间总是在UTC时间出现。我住在休斯顿,所以我知道时区是个问题。我已经按照链接中的代码进行了操作,但似乎可以获得当地时间。我做错了什么?
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?
推荐答案
要将UTC时间转换为本地,你必须使用 moment.local ()
。
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
演示:
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>
这篇关于时刻Js UTC到当地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!