【问题标题】:Javascript: Array of milliseconds to array of datesJavascript:毫秒数组到日期数组
【发布时间】:2020-03-26 03:52:37
【问题描述】:

当我尝试获取毫秒的输入数组并使用 Date() 将它们更改为日期时,我遇到了一些我不理解的行为。例如:

0: 1582641000
1: 1582727400
2: 1582813800
3: 1582900200
4: 1583159400
5: 1583245800
6: 1583332200
7: 1583418600
8: 1583505000
9: 1583760600
10: 1583847000

到目前为止,我已经使用了非常简单的函数来执行此操作,例如:

for (i = 0; i < timestamp.length; i++) {
    timestamp[i] = Date(timestamp[i]);
}

奇怪的是,至少对我来说,这使得“时间戳”的每个元素都具有相同的日期值。同样,如果我这样做:

for (i = 0; i < timestamp.length; i++) {
    timestamp[i] = new Date(timestamp[i]);
}

现在“timestamp”数组中的每个日期都是 1970 年 1 月 19 日。 这里发生了什么?如何从中获得正确的人类可读字符串数组?即:2020 年 3 月 25 日 20:50:00 GMT-0700 (PDT)?

【问题讨论】:

  • 先乘以 1000 将 UNIX 时间戳以秒为单位转换为毫秒,然后使用toLocaleDateString("en-US") 将其转换为日期时间格式。所以你可以这样做``timestamp[i] = new Date(timestamp[i] * 1000).toLocaleDateString("en-US");``
  • 我没有注意到我的数据以秒为单位,而不是毫秒超出了我的范围......

标签: javascript arrays date datetime


【解决方案1】:

Date 构造函数接受 毫秒 作为单个参数,而不是秒。先将数字乘以 1000。

您还必须使用new,否则生成的日期字符串将是当前时间not the timestamp of the parameter。 (没有new,所有参数都会被忽略)

使用.map 代替for 循环,并调用toUTCString

const arr = [
  1582641000,
  1582727400,
  1582813800,
  1582900200,
  1583159400,
  1583245800,
  1583332200,
  1583418600,
  1583505000,
  1583760600,
  1583847000,
];
const arrOfDates = arr.map(secs => new Date(secs * 1000).toUTCString());
console.log(arrOfDates);

【讨论】:

  • 我没有注意到我的数据以秒为单位,而不是毫秒超出了我的范围......
猜你喜欢
  • 2014-10-12
  • 1970-01-01
  • 2018-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多