如何使用来自 postgres 的带时区的 unix 时间戳格式化 D3 轴

How to format D3 axis using a unix timestamp with timezone from postgres

我正在尝试在 D3 折线图上设置 x 轴的格式,但值完全错误。 数据源自 Postgres 数据库 'timestamp with timezone' 列,我正在将其转换为 json 以通过 D3 提供。

D3 片段

data.forEach(function(d) {
    d.timestamp = new Date(d.timestamp*1000);
    d.close=+d.close;
}
var timeFormat = d3.time.format("%d %b %y %X");
var x = d3.time.scale().range([ 0, width ]);
var xAxis = d3.svg.axis().scale(x).orient("bottom").tickFormat(timeFormat);
x.domain(d3.extent(data, function(d) {
        return d.timestamp;
    }));

Java 转换为 JSON

ResultSet rs = st.executeQuery("select * from price_data order by timestamp);
...     
String.format("{\"timestamp\":\"%d\",\"close\":\"%f\"}",rs.getTimestamp("timestamp").getTime(),rs.getDouble("price"));

值为 1426014732000 的时间戳的轴格式化结果

不过我不明白的是,timeFormat 函数在单步执行我的 javascript 并通过 Chrome 中的监视表达式调用它时工作正常...

看起来你做的大部分事情都是对的,但如果没有完整的代码,就不太可能分辨出来。您如何为 scale 计算 domain?类似于:

x.domain(d3.extent(data));

无论如何,我整理了这个 simple example,可能会有帮助。

我仍然不知道为什么会发生这种情况,但解决方法是更改​​数据转换,而不是像网上到处建议的那样将时间戳乘以 1000。

data.forEach(function(d) {
  //d.timestamp = new Date(d.timestamp*1000);
  d.close=+d.close;
}
var timeFormat = d3.time.format("%d %b %y %X");
var x = d3.time.scale().range([ 0, width ]);
var xAxis = d3.svg.axis().scale(x).orient("bottom").tickFormat(timeFormat);
x.domain(d3.extent(data, function(d) {
        return d.timestamp;
    }));

现在时间戳已正确绘制。也许 PostgreSql 时间戳已经按照 Javascript 中的预期使用了毫秒。我会调查并向将来可能对此感兴趣的任何人报告。