[英]How to format D3 axis using a unix timestamp with timezone from postgres
I'm trying to format my x-axis on a D3 line chart, but the values are completely wrong. 我正在尝试在D3折线图上设置x轴的格式,但是值完全错误。 The data originates from a Postgres database 'timestamp with timezone' column which I'm converting to json to serve up via D3. 数据来自Postgres数据库的“带时区的时间戳”列,我将其转换为json,以通过D3提供服务。
D3 snippet 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 conversion to JSON 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"));
Result of axis formatting for timestamp with value 1426014732000 值为1426014732000的时间戳的轴格式化结果
What I don't understand though is that the timeFormat function works fine when stepping through my javascript and calling it via a watch expression in Chrome... 我不明白的是,当逐步浏览我的JavaScript并通过Chrome中的watch表达式调用它时,timeFormat函数可以正常工作...
Why this is happening I still don't know, but the fix was changing the data transformation to not multiply the timestamp by 1000 as suggested everywhere online. 为什么会发生这种情况,我仍然不知道,但解决方法是更改数据转换,以使时间戳不乘以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;
}));
Now the the timestamps are drawn correctly. 现在,正确绘制了时间戳。 Perhaps PostgreSql timestamps are already using milliseconds as expected in Javascript. 也许PostgreSql时间戳已经使用了Javascript中所期望的毫秒数。 I will investigate and report back for anyone who might be interested in this in future. 我将进行调查并向将来提出报告的人反馈。
Looks as though you're doing most things right, but without the full code it's not really possible to tell. 看来您在做大多数事情都是对的,但是如果没有完整的代码,这实际上是不可能的。 How are you computing the domain
for the scale
? 您如何计算scale
domain
? Something like: 就像是:
x.domain(d3.extent(data));
Regardless, I've put together this simple example , which may help. 无论如何,我整理了这个简单的示例 ,可能会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.