Reputation: 3668
I have two date. And i wanted to create a array with the number of days between them.
I've done it successfully. And here's the code.
Code :
var data = []; var start = new Date('2014-02-01'); var end = new Date('2014-02-28'); var timeDiff = Math.abs(end.getTime() - start.getTime()); var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
for ( var i = 0; i < diffDays; ++i ) {
var date = new Date(start)
date.setDate(start.getDate() + i)
var dd = date.getDate();
var mm = date.getMonth() + 1;
var yyyy = date.getFullYear();
formattedDate = mm + '/' + dd + '/' + yyyy
data.push(formattedDate)
}
And i got the array for the number of days between it.
But now i'm looking a bit forward.
I wanted to add another column.
Suppose i have these following date.
['2014-02-05', '2014-02-10']
. I wanted to add another column like date2 which will have -
value for all the rows except the row where the date generated dynamically and the above two date matches.
Someone please help me in creating data for two column dynamically.
Expected Output :
{ "date": "2014-02-01", "date2": "-" }, { "date": "2014-02-02", "date2": "-" } { "date": "2014-02-03", "date2": "2014-02-03" } { "date": "2014-02-04", "date2": "-" } { "date": "2014-02-05", "date2": "2014-02-05" } { "date": "2014-02-06", "date2": "-" }
Upvotes: 0
Views: 295
Reputation: 6192
You can do something like
var data = [];
var start = new Date('2014-02-01');
var end = new Date('2014-02-28');
var dateFormat = d3.time.format('%Y-%m-%d');
var specialDates = ['2014-02-05', '2014-02-10'];
var newData = d3.time.day.range(start, end).map(
function(d){
var thisDateString = dateFormat(d);
if (specialDates.indexOf(thisDateString) < 0)
return {'date':thisDateString, 'date2':'-'}
else
return {'date':thisDateString, 'date2':thisDateString}
}
)
Have a look at this JSFiddle
We are using d3.time.day.range(start, end)
to give us an array of days. Then by using .map
we create a new array. What are the values of this shiny new array? Whatever is retuned for each item in the original array when passed into the function we define (so anything we want).
Upvotes: 2
Reputation: 6192
You can create an array of dates easily with d3
d3.time.day.range(start, end)
You can use any of the intervals in the documentation which currently are
Upvotes: 0