在D3.js问题中解析时间戳

发布于 2025-02-08 13:48:28 字数 442 浏览 2 评论 0原文

我正在尝试解析d3.js中的图中使用的时间戳,但我无法设法使其正常工作。时间戳的示例如下所示:

 - 2022-02-17 09:52:37.000000
 - 2022-02-17 09:54:00.000000

我用来进行解析的代码是:

`const dateParser = d3.timeFormat("%Y-%m-%d");

data.forEach(function(d) {
        d.timestamp = dateParser(d.ts);
    });`
  

其中d.ts是时间戳

我目前获得的输出以下是:

  • 0nan-- Nan-nan

提前谢谢

I am trying to parse a timestamp to use in a plot in d3.js but I cannot manage to get it to work. Examples of the timestamp are shown below:

 - 2022-02-17 09:52:37.000000
 - 2022-02-17 09:54:00.000000

The code that I use to do the parsing is:

`const dateParser = d3.timeFormat("%Y-%m-%d");

data.forEach(function(d) {
        d.timestamp = dateParser(d.ts);
    });`
  

Where d.ts is the timestamp

The output I get at the moment is under the form:

  • 0NaN-NaN-NaN

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

若能看破又如何 2025-02-15 13:48:29

是您的日期字符串吗?如果是这样,您可以将代码更改为首先将字符串日期转换为日期对象,然后在其上调用DateParser:

data.forEach(function(d) {
        d.timestamp = dateParser(new Date(d.ts));
});

Are your dates strings? If so you could change your code to first convert the string date to Date object and then call dateParser on it:

data.forEach(function(d) {
        d.timestamp = dateParser(new Date(d.ts));
});
时光匆匆的小流年 2025-02-15 13:48:28

从某种意义上说,解析 formatting 的反面注意您的指定器,这是不正确的)。

因此,您需要d3.TimeParse()。这是工作片段,查看浏览器的控制台,而不是摘要的片段:

const dates = ["2022-02-17 09:52:37",
  "2022-02-17 09:54:00"
];

const dateParser = d3.timeParse("%Y-%m-%d %H:%M:%S");

dates.forEach(function(d) {
  console.log(dateParser(d));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

In a way, parsing is the opposite of formatting: when you parse you convert a string to a date, while formatting is converting the date to a readable string (also, pay attention to your specifier, it's incorrect).

Therefore, you want d3.timeParse() instead. Here is the working snippet, look at your browser's console, not the snippet's one:

const dates = ["2022-02-17 09:52:37",
  "2022-02-17 09:54:00"
];

const dateParser = d3.timeParse("%Y-%m-%d %H:%M:%S");

dates.forEach(function(d) {
  console.log(dateParser(d));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文