如何将以毫秒为单位的时间戳转换为 javascript ? (在反应中)

how to convert Timestamp in milliseconds to javascript ? (in React)

考虑下面的代码,

const appointments = [

  {
    // id: 0,
  title: 'Watercolor Landscape',
  users_id: 2,
    startDate: new Date(1584576000000 * 1000),   // here is timestamps in milliseconds 
    endDate:  new Date(1584662400000* 1000),       // here is timestamps in milliseconds
    ownerId: 1,
  },
];

但是 startDate 的输出是错误的,:

应该是:

开始日期:2020 年 3 月 19 日,星期四 8:00:00 AM GMT+08:00

结束日期:2020 年 3 月 20 日,星期五 8:00:00 AM GMT+08:00

在我看来,您只需删除 * 1000,一切都会正常进行:

console.log(new Date(1584576000000))
// Thu Mar 19 2020 02:00:00 GMT+0200

console.log(new Date(1584662400000))
// Fri Mar 20 2020 02:00:00 GMT+0200

请简单地使用:new Date(your_timestamps)
所以在你的代码中:startDate: new Date(1584576000000)

在此处阅读 Javascript 中有关 Date 对象的更多信息 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

unix 时间戳已经以毫秒为单位,Date.now() 获取以毫秒为单位的时间戳!

要在 内获得 unix 时间戳,您需要将其除以 1000

Math.floor(Date.now() / 1000)

要在 JS 中获取以毫秒为单位的时间戳,您可以这样做:

var date = new Date();
var timestamp = date.getTime();

如果您不打算支持 IE8 或以前的版本,您可以使用:

Date.now();

注意:时间戳是自 1970 年 1 月 1 日以来经过的毫秒数。

阅读更多here