Moment.js how do you get the current Quarter and previous three quarters along with year? Moment.js how do you get the current Quarter and previous three quarters along with year? angularjs angularjs

Moment.js how do you get the current Quarter and previous three quarters along with year?


Here's a solution using Moment.js:

const moment = require('moment');let fmt      = '[q]Q-Y';let quarters = [  moment().format(fmt),  moment().subtract(1, 'Q').format(fmt),  moment().subtract(2, 'Q').format(fmt),  moment().subtract(3, 'Q').format(fmt)];// quarters = [ 'q3-2016', 'q2-2016', 'q1-2016', 'q4-2015' ]

Or a more concise version:

let quarters = [ 0, 1, 2, 3 ].map(i =>   moment().subtract(i, 'Q').format('[q]Q-Y'))


var d = new Date();//current date    var y = d.getFullYear();//year as 4 digit number    var m = d.getMonth();//0 to 11 which actually is helpful here    var q = Math.floor(m / 3) + 1;//month div 3 + 1    var s = "";//this holds the result    for (var i = 0; i < 4; i++) {        s += "q" + q + "-" + y;        if (i < 3) {            s += " ";//another entry coming so put in space            q--;//and roll back quarter        }        if (q == 0) {            q = 4;//we were in q1 so predecessor is q4            y--;//and the year is one less        }    };console.log(s);