how to format time on xAxis use d3.js
I want to add this link to an awesome demo page. It is a playground when you can choose what a format specifier do you need for your case. It is very useful when you do not remember/know what a format specifier you should pass to your d3.timeFormat
function.
I also want to notice, that if you have d3 version 4, you should use d3.timeFormat
function, instead of d3.time.format
.
You can use the tickFormat function on the axis object as below
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(d3.time.format("%H"));
The %H
specifies hour (24-hour clock) as a decimal number [00,23]
. Check this link D3 time formatting for more information
You can check out a working example in this tributary 24hr time example
The accepted answer is indeed correct, but in my case, I needed the flexibility for the formats to adjust to different scales (think zooming), but also to ensure the 24hr clock is used. The key is to define a multi-resolution time format. See the Documentation page for details.
My code:
var axisTimeFormat = d3.time.format.multi([
[".%L", function(d) { return d.getMilliseconds(); }],
[":%S", function(d) { return d.getSeconds(); }],
["%H:%M", function(d) { return d.getMinutes(); }],
["%H:%M", 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; }]
]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(axisTimeFormat);