In the spirit of teaching, see comments:
var stopDate = new Date("2014-09-04"); // One day AFTER the last date we care
// about
var results = []; // An array for our results, initially
// empty
var date = new Date("2014-08-28"); // Our starting date
var entry; // The "current" month's entry in the loop
while (date < stopDate) {
// Create a new entry if necessary.
// The `!entry` bit uses the fact that variables start out with the value
// `undefined`, and `undefined` is "falsey", so `!entry` will be true if
// we haven't put anything in `entry` yet. If we have, it's an object
// reference, and object references are "truthy", so `!entry` will be
// false. The second check is to see whether we've moved to a new month.
if (!entry || entry.month !== date.getMonth() + 1) {
// Create a new entry. This creates an object using an object initialiser
// (sometimes called an object "literal")
entry = {
month: date.getMonth() + 1, // +1 because `getMonth` uses 0 = January
days: 0 // Haven't counted any days yet
};
// Add it to the array
results.push(entry);
}
// Count this day
++entry.days;
// Move to next day
date.setDate(date.getDate() + 1); // JavaScript's `Date` object handles
// moving to the next month for you
}
About “falsey” and “truthy”: In most languages, you can only use booleans (true or false) for branching, but JavaScript allows coercing values to booleans. “Falsey” values are values that coerce to false. They are: undefined
, null
, NaN
, 0
, ""
, and of course false
. “Truthy” values are everything else.
4
solved JavaScript : How to calculate days count from two dates based on month