admin管理员组

文章数量:1201158

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

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

Share Improve this question asked Aug 24, 2016 at 2:56 josh_boazjosh_boaz 2,0237 gold badges35 silver badges74 bronze badges 1
  • What is your definition of "quarter"? Different administrative classifications have different definitions (e.g. calendar vs financial year, and financial year in different jurisdictions). – RobG Commented Aug 24, 2016 at 5:43
Add a comment  | 

3 Answers 3

Reset to default 19

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

Presuming you want calendar quarter (i.e. Q1 is Jan to Mar inclusive, Q2 Apr to Jun inclusive, etc.) then an approach like Jeremy's works. The following is similar, just a bit more creative with some array methods.

If you you have some other definition of "quarter" (e.g. Jul-Sep inclusive is often Q1 financially, and Apr-Jun is Q4 of the previous year), then set the initial value of q accordingly.

function getQuarters() {
  var d = new Date().toISOString().split('-').splice(0,2);
  var q = Math.ceil(d[1] / 3);
  return new Array(4).fill(null).reduce(function(acc, v,i, arr) {
    arr[i] = 'q' + q + '-' + d[0];
    d[0] -= q==1? 1 : 0;
    q    -= q > 1? 1 : -3;
    return arr;
  }, null);
}

console.log(getQuarters())

本文标签: