Ad

Get Last N Quarters In JavaScript

- 1 answer

Apparently, this kind of question was asked before, but it's a C# answer that I can't translate into JavaScript.

Here's my original code, but it now fails for the first quarter:

var amount = 6;
var now = new Date();
var thisYear = now.getFullYear();
var quarterStart = Math.ceil((now.getMonth() + 1) / 3);
//quarterStart will return a number between 1 and 4

for (var i = 0; i < amount; i++) {

    //here's the line that definitely needs to be changed
    var thisQuarter = quarterStart - (i % 4);

    //if thisQuarter is the last one, go back one year
    if (thisQuarter == 4 && i > 0) {
        thisYear--;
    };

    console.log('Q' + thisQuarter + ' ' + thisYear);
};

//console should return the following
//'Q1 2016'
//'Q4 2015'
//'Q3 2015'
//'Q2 2015'
//'Q1 2015'
//'Q4 2014'

EDIT: The setup for the loop can be changed, as long as the output is as shown.

Ad

Answer

I've made some changes to your code, should work now.

var amount = 6;
var now = new Date();
var thisYear = now.getFullYear();
var quarterStart = Math.ceil((now.getMonth() + 1) / 3);

for (var i = 0; i < amount; i++) {
    console.log('Q' + quarterStart + ' ' + thisYear);

    quarterStart--;
    if (quarterStart <= 0) {
        thisYear--;
        quarterStart = 4;
    };
};
Ad
source: stackoverflow.com
Ad