使用 D3 进行纪元时间转换

Epoch Time conversion with D3

本文关键字:时间 转换 纪元 D3 使用      更新时间:2023-09-26

这似乎是一个微不足道的问题,但我得到一个奇怪的错误:

"未捕获的类型错误:t.slice 不是一个函数"

尝试将 UNIX 时间戳传递给我的代码时。

var myDate = new Date(1075611600000);
  var format = d3.time.format("%Y").parse; //Trying to return the year.
  console.log(format(myDate)); //error noted above
  console.log(myDate); //Sun Feb 01 2004 00:00:00 GMT-0500 (EST)

有人看到我犯的明显错误了吗?提前谢谢。我看了这个例子,我看不出我做错了什么。我试图只返回一年。

format函数需要一个字符串,而你传入一个没有slice函数的Date对象。

我相信这就是你想要实现的:

var format = d3.time.format("%Y-%m-%d");
console.log(format(new Date(1075611600000))); // returns a string

[杰斯菲德尔]

https://github.com/mbostock/d3/wiki/Time-Formatting

您正在将Date传递给您的parse方法,您应该在其中传递一个string

如果你想从Date中得到一个string,不要使用.parse()


PS:您使用的是缩小的d3,因此Uncaught TypeError: t.slice is not a function代表:

Uncaught TypeError: string.slice is not a function
d3_time_parseFullYear @ d3.js:2760
d3_time_parse @ d3.js:2563
format.parse @ d3.js:2538