【问题标题】:ISO8601 Date Time format D3ISO8601 日期时间格式 D3
【发布时间】:2015-07-01 03:01:11
【问题描述】:

我正在尝试在我的 D3 折线图上显示时间戳。我的数据是 JSON。日期如下所示:'2015-04-02T23:10:00'。目前,它的格式如下: var timeFormat = d3.time.format('%Y-%m-%dT%H:%M:%S'); 在图表上时,它以这种方式显示: 2015 年 6 月 29 日星期一 09:50:00 GMT-0500(中部夏令时间)

我希望能够对其进行格式化,使其仅显示时间。例如,09:50:00。我已经尝试过 timeFormat 到不同的东西,但没有奏效。任何建议,将不胜感激。

【问题讨论】:

  • 你见过this tutorial吗?
  • 你试过什么不同的?
  • @Bergi,我尝试将 d3.time.format('%Y-%m-%dT%H:%M:%S') 更改为 ('%I:%M: %p') 和 ('%H:%M:%S')。
  • 你如何使用这个timeFormat?看起来不是用来显示的,而是用来解析的。
  • 将时间添加到图表时,我使用这个 d3.select('#time').text(formatOutput4(d));格式输出是这样的: var formatOutput4 = function (d) { return timeFormat.parse(d.metricDate); };

标签: javascript d3.js iso8601


【解决方案1】:

您需要区分解析和字符串化/格式化。所以使用

var inputFormat = d3.time.format.iso; // or d3.time.format('%Y-%m-%dT%H:%M:%S');
var outputFormat = d3.time.format('%I:%M:%p'); // or whatever

然后做

d3.select('#time').text(formatTime(d));
function formatTime(d) {
    return outputFormat(inputFormat.parse(d.metricDate));
}

(虽然理想情况下metricDate不会是字符串,而是加载原始数据时解析日期的结果日期对象)

请参阅https://github.com/mbostock/d3/wiki/Time-Formatting 以获取更多参考。

【讨论】:

  • 非常感谢您帮我调查这个问题。但是,我将此更改添加到我的代码中,但它不起作用。我假设这是因为我的代码存在更大的问题。我得到的错误是:Uncaught TypeError: Cannot read property 'metricDate' of undefined.
  • 不,我搞砸了,d 的范围不同。现在看起来像您评论中的代码。
  • 没关系!哪个评论?我有点困惑。
  • @CrashleyS: That one.
猜你喜欢
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 2022-09-28
  • 1970-01-01
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多