Looping Through Dates with Javascript

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:

  • endDate - Date - the date to iterate to. It can be earlier or later than date object.
  • part - String - The date part to adjust. See adjust method linked to above.
  • step - Number - Positive integer of the amount to increment the part of the date.
  • fn - Function - The callback function for each iteration. Return false to break loop.

The callback function also has three arguments available:

  • currentDate - Date - The Date object of the current iteration.
  • currentStep - Number - The current iteration step. From 0 it increases by step each iteration.
  • thisDate - Date - 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!