JEJoll
JEJoll

Reputation: 547

d3 - Format an integer as time on 24 hour clock

I've seen other questions similar to this, but mine is a bit of a unique case.

I'm plotting points from a simulator which collects data every 9 seconds for a 24 hour period. This returns an array containing 9600 values.

Currently, I'm displaying just whole numbers by converting the array's index to an integer between 0 and 24 by multiplying it by 0.0025 (9 / 60 /60 == 0.0025). So 9600 * .0025 == 24.

However, I'd like to be able to display half and quarter hours as well, so 1:15 AM would show as 1:15, and 3:30 PM would display as 15:30.

How can I do this?

Upvotes: 0

Views: 3265

Answers (2)

Kamil Latosinski
Kamil Latosinski

Reputation: 846

In case someone has a range of integers and wants to use them as hours when displaying ticks here is a solution for v4:

var yScale = d3.scaleLinear()
    .domain(timeExtent) // [6, 20] from 06:00 to 20:00
    .range([0, height - cellHeight]);

var yAxis = d3.axisLeft(yScale)
    .tickFormat(function (hour) {
        var now = new Date();
        now.setHours(hour, 0, 0, 0);
        return d3.timeFormat("%H:%M")(now);
    });

Upvotes: 0

Brad-
Brad-

Reputation: 56

If I understand correctly it might be easier to set a base date at midnight and then add to it to so you can use d3.time.format, some form of the below.

var i = 4800
var date = new Date();
date.setHours(0,0,0,0); //set date to midnight

var format = d3.time.format("%H:%M %p") //format to Hour Minutes
date.setSeconds(date.getSeconds() + (9 * i)); //9*4800 for Noon

alert(format(date)) //Alerts 12 P.M.

Then use a tick format for the axis for every quarter hour that's similar to below

d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .ticks(d3.time.minutes, 15)
    .tickFormat(d3.time.format("%H:%M"));

Upvotes: 2

Related Questions