Working with quarters in JavaScript

Today my friend was working on a tool and a part of his task was to define a quarter of a given date and also to define its borders. I had spare time and tried to join this job.

The first thing we did was googling for it, and the result was this helpful topic: Math.floor((date.getMonth() + 3) / 3), but after that the task of finding start and end dates of a quarter still remained.

While I was busy with monkey coding this function:

function getQuarterBounds(date) {
    date = date || new Date();

    var q = Math.floor((date.getMonth() + 3) / 3);
    var year = date.getFullYear();
    var quarters = {
        1: {
            start: '01-01',
            end: '03-31'
        }, 2: {
            start: '04-01',
            end: '06-30'
        }, 3: {
            start: '07-01',
            end: '09-30'
        }, 4: {
            start: '10-01',
            end: '12-31'
        }
    };

    return [
        new Date(year + '-' + quarters[q].start),
        new Date(year + '-' + quarters[q].end)
    ];
}

My friend noticed that setMonth() function has a second argument which is a day, and when it is equal to 0 then the result date will be the last day of a previous month, -1 sets one more day before that day and so on.

This functionality was very helpful in our case:

function getQuarterBounds(date) {
    date = date || new Date();

    return [
        new Date(new Date().setMonth(
            date.getMonth() - date.getMonth() % 3, 1)),
        new Date(new Date().setMonth(
            date.getMonth() + 3 - date.getMonth() % 3, 0))
    ];
}

Year, sometimes you have to recall sad “RTFM” expression

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>