Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define custom time interval in d3.js

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.

like image 493
Cihad Turhan Avatar asked Nov 28 '13 23:11

Cihad Turhan


People also ask

What is a D3 interval?

For d3. timer(), delay is a one-off delay before starting the timer, after which the callback function is invoked repeatedly. For d3. interval(), the delay is applied repeatedly between calling the callback , producing the 'intervals'.

What is D3 v3 min JS?

D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG, and CSS.


2 Answers

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)

like image 150
Logan Avatar answered Oct 15 '22 15:10

Logan


You are looking for this example: http://bl.ocks.org/mbostock/4149176

Working example for your case: http://bl.ocks.org/musically-ut/7699650

Code from example

function timeFormat(formats) {
  return function(date) {
    var i = formats.length - 1, f = formats[i];
    while (!f[1](date)) f = formats[--i];
    return d3.functor(f[0])(date);
  };
}

var customTimeFormat = timeFormat([
  [d3.time.format("%Y"), function() { return true; }],
  [d3.time.format("%B"), function(d) { return d.getMonth(); }],
  [d3.time.format("%b %d"), function(d) { return d.getDate() != 1; }],
  [d3.time.format("%a %d"), function(d) { return d.getDay() && d.getDate() != 1; }],
  [d3.time.format("%I %p"), function(d) { return d.getHours(); }],
  [d3.time.format("%I:%M"), function(d) { return d.getMinutes(); }],
  [d3.time.format(":%S"), function(d) { return d.getSeconds(); }],
  [d3.time.format(".%L"), function(d) { return d.getMilliseconds(); }]
]);

var xAxis = d3.svg.axis()
    .scale(x) // x is a scale.
    .tickFormat(customTimeFormat);

In your case, you want something of this kind:

var customTimeFormat = timeFormat([
  ["00:00", function () { return true; }],
  ["06:00", function (d) { return 3 <= d.getHours() && d.getHours() < 9; }],
  ["12:00", function (d) { return 9 <= d.getHours() && d.getHours() < 15; }],
  ["18:00", function (d) { return 15 <= d.getHours() && d.getHours() < 21; }]
]);
like image 42
musically_ut Avatar answered Oct 15 '22 16:10

musically_ut