Reputation: 3245
I'm using D3.js (v3) to plot a time-series graph and I'm trying to figure out the amount of ticks I need for a given month (ie, days). From what I can make of the documentation, d3.time-month
should return something from 28 to 31 days, which is what I want, but for some reason I'm obviously missing, I can't seem to get the number I need.
Can anyone help?
This is what I've got so far:
console.log(date); // Fri Jul 01 2016 00:00:00 GMT+0100 (WEST)
monthDays = d3.time.month(date);
console.log(currentMonth+" has "+monthDays+" days."); // July has Fri Jul 01 2016 00:00:00 GMT+0100 (WEST) days.
Upvotes: 1
Views: 2094
Reputation: 33344
You're misreading the documentation on intervals : the number of days in the intervals used by d3.time.month
have a length between 28 and 31 but the functions are defined as
interval(date)
Alias for
interval.floor(date)
. [...]
and
interval.floor(date)
Rounds down the specified date, returning the latest time interval before or equal to date. [...]
Basically, d3.time.month(date)
will return the first day of the month at midnight, not the number of days in that month.
How to get the number of days then? As far as I can tell, D3 does not expose a way to get the length of the month for a given date. You could of course get the range of days for a given month and extract its length:
var date = new Date(2016, 01, 02); // 2016-02-02
console.log(
d3.time.days(d3.time.month(date), d3.time.month.ceil(date)).length
)
or probably more efficiently use plain JS like in this answer https://stackoverflow.com/a/1185804/1071630 :
var date = new Date(2016, 01, 02); // 2016-02-02
console.log(
new Date(date.getFullYear(), date.getMonth()+1, 0).getDate()
)
var date = new Date(2016, 01, 02);
console.log(
d3.time.days(d3.time.month(date), d3.time.month.ceil(date)).length
)
console.log(
new Date(date.getFullYear(), date.getMonth()+1, 0).getDate()
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Upvotes: 1