首页 > 解决方案 > 我需要从“1609891200000”开始的正确时间而不使用 Moment

问题描述

var now = moment(1609891200000, "x").format('MMM DD h:mm A');
var x = new Date(1609891200000);
console.log(now); // Prints Jan 06 12:00 AM
console.log(x.toLocaleTimeString()); // Prints 05:30:00

我不知道为什么我的时间一直在 5:30。我需要一种方法来获得正确的时间,即12:00 AM不使用 Moment。

我怎样才能做到这一点?

标签: javascriptdatemomentjsmoment-timezone

解决方案


您应该提供时区代码,如果没有代码,则默认提供

var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));

// toLocaleTimeString() without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(date.toLocaleTimeString());
// → "7:00:00 PM" if run in en-US locale with time zone America/Los_Angeles

相反,您可以使用

var x = new Date(1609891200000);
x.toGMTString() // "Wed, 06 Jan 2021 00:00:00 GMT"
x.toUTCString() // "Wed, 06 Jan 2021 00:00:00 GMT"
x.toISOString() // "2021-01-06T00:00:00.000Z"

推荐阅读