ua_boaz ua_boaz - 3 months ago 42
AngularJS Question

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

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

Answer

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