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

10,022

Solution 1

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')
)

Solution 2

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);

Share:
10,022
josh_boaz
Author by

josh_boaz

Updated on July 18, 2022

Comments

  • josh_boaz
    josh_boaz almost 2 years

    is there a way to get current quarter and previous three quarters along with year, for example it should return four quarters like this

    q3-2016 q2-2016 q1-2016 q4-2015

  • Jeremy Kahan
    Jeremy Kahan over 7 years
    Thanks @RobG. I learned something new. I edited the code per your suggestion.
  • JEEVAN GEORGE ANTONY
    JEEVAN GEORGE ANTONY almost 6 years
    As per Latest momen.js format, if you are following above custom format then you need to change it from '[q]Q-Y' to '[q]Q-YYYY' .