How to define custom time interval in d3.js

d3.js, javascript

Solution

Here's my solution which makes use of built-in d3 functions:

function another6HourRound(date) {
    var subHalf = d3.time.hour.offset(date, -3);
    var addHalf = d3.time.hour.offset(date, 3);
    return d3.time.hours(subHalf, addHalf, 6)[0];
}

Returns the nearest 6 hour interval (on 00, 06, 12, or 18)

Problem

I'm trying to code an interval round function using the `d3.js` time intervals API. The thing I want to do is fairly simple: write a function that rounds a time to the nearest 6 hours and returns it as a `Date` object. For example: - At 10:30, `d3.hour.my6HourRound(new Date)` should return 12:00 today - At 12:30, `d3.hour.my6HourRound(new Date)` should return 12:00 today - At 23:50, `d3.hour.my6HourRound(new Date)` should return 00:00 tomorrow It must not be so difficult, but `d3.js` api lacks of usage demos in API.

Original source