Earlier in the week I posted an adjust and a diff function for the javascript Date object. Since I was on a roll with the dates I thought I would throw another one in there as it seems to just go hand in hand. This method is an “each” method. It requires a few arguments, but it saves you some headache. The arguments are as follows:

  • endDateDate – the date to iterate to. It can be earlier or later than date object.
  • partString – The date part to adjust. See adjust method linked to above.
  • stepNumber – Positive integer of the amount to increment the part of the date.
  • fnFunction – The callback function for each iteration. Return false to break loop.

The callback function also has three arguments available:

  • currentDateDate – The Date object of the current iteration.
  • currentStepNumber – The current iteration step. From 0 it increases by step each iteration.
  • thisDateDate – The original Date object.

Ok, that tells us how to use it, lets see the method itself:


Date.prototype.each = function(endDate, part, step, fn, bind){
	var fromDate = new Date(this.getTime()),
		toDate = new Date(endDate.getTime()),
		pm = fromDate <= toDate? 1:-1,
		i = 0;

	while( (pm === 1 && fromDate <= toDate) || (pm === -1 && fromDate >= toDate) ){
		if(fn.call(bind, fromDate, i, this) === false) break;
		i += step;
		fromDate.adjust(part, step*pm);
	}
	return this;
}

As you can see it simply extends the Date object with a new property. Now all we need is to create two dates, the from date and the to date. Also be aware you MUST have the Date.adjust method available. Together they work in harmony. Lets take a look at an example usage.


var d1 = new Date(),
	d2 = new Date();

d2.adjust('days', 450);

// loop by weeks
d1.each(d2, 'weeks', 1, function(currentDate, currentStep, thisDate){
	console.log(arguments); // Open your console!
});

// loop by months
d1.each(d2, 'months', 1, function(currentDate, currentStep, thisDate){
	console.log(arguments); // Open your console!
});

Don’t worry if your endDate is before or after the original date, that is taken care of for you. Just always supply a positive step value and watch it work. Hope you’ve enjoyed this new date extension!