【问题标题】:How to make D3.js use UTC times for the x-axis, with Moment.js如何使用 Moment.js 使 D3.js 使用 UTC 时间作为 x 轴
【发布时间】:2017-05-25 17:53:00
【问题描述】:

我正在使用 D3.js 为 x 轴绘制一个带有 UTC 时间刻度的可缩放图表,例如:

var axisTimeFormat = d3.time.format.utc.multi([
    [".%L", function(d) { return d.getMilliseconds(); }],
    [":%S", function(d) { return d.getSeconds(); }],
    ["%I:%M", function(d) { return d.getMinutes(); }],
    ["%I %p", function(d) { return d.getHours(); }],
    ["%a %d", function(d) { return d.getDay() && d.getDate() != 1; }],
    ["%b %d", function(d) { return d.getDate() != 1; }],
    ["%B", function(d) { return d.getMonth(); }],
    ["%Y", function() { return true; }]
]);

// `minDt` and `maxDt` are Moment.js UTC times:
var x = d3.time.scale.utc()
          .domain([minDt, maxDt])
          .range([0, width]);

var xAxis = d3.svg.axis().scale(x)
              .orient('bottom')
              .tickSize(-height)
              .tickFormat(axisTimeFormat);

我的数据使用 Moment.js UTC 时间。一切正常,但问题是刻度始终采用“%I %p”格式,无论我放大或缩小多少。

我在伦敦,在夏令时期间,所以在 d3.time.format.utc.multid.getHours() 返回 113,而不是 0(这将导致它下降到下一次格式)或12

这些函数中使用的 Date 对象似乎不再是 UTC。即,如果我在其中一个中执行console.log(d),我会得到类似:

Tue May 16 2017 01:00:00 GMT+0100 (BST)

我怎样才能让这些使用我在其他地方使用的 UTC 日期?

【问题讨论】:

  • 我在你的代码中根本看不到时刻。如果你真的通过yourUtcMomentObject.toDate() 得到了d,那么就不要打电话给toDate。您可以从 moment 的 getter 中获取值,例如 .hour() 等。
  • minDtmaxDt,用于生成 D3 刻度,都是 Moment 时间。但是d,在d3.time.format.utc.multi()中的函数内都是标准的JS日期。

标签: javascript d3.js momentjs


【解决方案1】:

您可以在axisTimeFormat 定义中使用UTC 方法。

尝试替换

return d.getHours();

return d.getUTCHours();

等等

【讨论】:

  • 就是这样!谢谢!我今天早些时候在我的时区冒险中注意到了这些方法,然后就忘记了它们。
猜你喜欢
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多