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
3 Answers
Reset to default 19Here'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())
本文标签:
版权声明:本文标题:javascript - Moment.js how do you get the current Quarter and previous three quarters along with year? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738619224a2103095.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论