Creating a periodic array of dates in JavaScript

So I am lazy – nothing new there. I am also a manager (nothing new there either unfortunately) and I track hours in a spreadsheet. Yes we have a proper system for hours tracking and billing but I am old school and I prefer the layout I created and have used for yeeeears.

Anyway, so it is new project time and I need to create a set of dates from this Friday – every Friday out through the next 3 months. I am sure there is a smart way to do that in Excel but I wanted to do it in JavaScript – ‘cos I can, and ‘cos I want to keep kidding myself I am a developer😉

A quick Google search found this snippet which is almost what I was looking for http://stackoverflow.com/a/4413721/1171653 (look at the example)

I modified the sample code slightly to return the format I was looking for – starting today – 02/26/2015

Date.prototype.addDays = function(days) {
    var dat = new Date(this.valueOf())
    dat.setDate(dat.getDate() + days);
    return dat;
}

function getDates(startDate, stopDate) {
    var dateArray = new Array();
    var currentDate = startDate;
    while (currentDate <= stopDate) {
        var day = currentDate.getDate()
        var month = currentDate.getMonth()+1
        var year = currentDate.getFullYear()
        dateArray.push(day+"/"+month+"/"+year )
        currentDate = currentDate.addDays(7);
    }
    return dateArray;
}

var dateArray = getDates((new Date()).addDays(2), (new Date()).addDays(90));

console.log(dateArray)

Loaded it into the firebug console and produced the following which is easily copy/pasteable into Excel

[“28/2/2015”, “7/3/2015”, “14/3/2015”, “21/3/2015”, “28/3/2015”, “4/4/2015”, “11/4/2015”, “18/4/2015”, “25/4/2015”, “2/5/2015”, “9/5/2015”, “16/5/2015”, “23/5/2015”]

It took me longer to write this up on the blog than do it.

But now I have a reference point so that when I need it for the next project I can come and get this code🙂

Lazy🙂

3 thoughts on “Creating a periodic array of dates in JavaScript

  1. [1:17:28 PM] Simon Reid: Well in Excel you would put in this friday in the first cell, next friday in the next cell, and then select both cells and then click on the bottom right corner of the selection and drag down as far as you want.

    Apparently there is a really easy way to do it in excel – who knew !!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s