0

Say I have some data that can span anywhere from 28-31 days. I don't know how many days the data spans, but I know the beginning and ending date, and I create a d3 time scale using the two dates as the domain.

If I specify that I want 1 tick per day, is there a way to get the axis to return how many ticks it's going to create?

Or put another way, is there another method to determine in Javascript how many days are in a range of two dates?

mgerring
  • 53
  • 1
  • 6
  • possible duplicate http://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript – JBaczuk Feb 05 '15 at 01:15

1 Answers1

1

Check out d3.time.day. It's what d3.time.scale uses to do "time math". It's kinda hard to figure how to use, but it looks like there's a method that'll return every day between two dates (represented as a Date object at midnight of each day).

For example, here are the days that elapsed between Jan 24th and now:

d3.time.day.range(new Date(2015,0,24), new Date())
/* returns
[
  Sat Jan 24 2015 00:00:00 GMT-0500 (EST),
  Sun Jan 25 2015 00:00:00 GMT-0500 (EST), 
  Mon Jan 26 2015 00:00:00 GMT-0500 (EST), 
  ...
  Tue Feb 03 2015 00:00:00 GMT-0500 (EST),
  Wed Feb 04 2015 00:00:00 GMT-0500 (EST)
]
*/

So then you can take the .length of that array and there you have it... There are also equivalent functions for counting hours, weeks, months etc.

Maybe there's also a way to get just the number of days — without producing the actual array of Dates — but I couldn't find one.

meetamit
  • 24,727
  • 9
  • 57
  • 68
  • You could also create the axis, select the tick elements and then get the length of that selection. And delete the axis immediately afterwards if you don't need it. – Lars Kotthoff Feb 05 '15 at 09:36
  • 1
    I ended up just doing a raw elapsed time calculation, BUT, this answer helped me solve another related problem and I'll probably end up using this. Thanks! – mgerring Feb 05 '15 at 21:40