繁体   English   中英

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

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

我正在尝试在D3折线图上设置x轴的格式,但是值完全错误。 数据来自Postgres数据库的“带时区的时间戳”列,我将其转换为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的时间戳的轴格式化结果 错误的轴显示格式解释

我不明白的是,当逐步浏览我的JavaScript并通过Chrome中的watch表达式调用它时,timeFormat函数可以正常工作... 在此处输入图片说明

为什么会发生这种情况,我仍然不知道,但解决方法是更改​​数据转换,以使时间戳不乘以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中所期望的毫秒数。 我将进行调查并向将来提出报告的人反馈。

看来您在做大多数事情都是对的,但是如果没有完整的代码,这实际上是不可能的。 您如何计算scale domain 就像是:

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

无论如何,我整理了这个简单的示例 ,可能会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM