How can I get the current quarter we are in with javascript? I am trying to detect what quarter we are currently in, e.g. 2.
EDIT And how can I coun
This worked for me!
var d = new Date();
var quarter = Math.ceil(d.getMonth() / 3);
console.log(quarter)
You can use moment package:
Answer of your question using moment package is:
moment().quarter()
Below are the start and end dates of a quarter using the moment package:
START DATE OF QUARTER
moment().quarter(moment().quarter()).startOf('quarter');
Would return the current quarter with the date set to the quarter starting date.
moment("2019", "YYYY").quarter(4).startOf('quarter');
Would return the starting date of the 4th quarter of the year "2019".
moment().startOf('quarter');
Would return the starting date of the current quarter of current year.
END DATE OF QUARTER
moment().quarter(moment().quarter()).endOf('quarter');
Would return the current quarter with the date set to quarter ending date.
moment("2019", "YYYY").quarter(4).endOf('quarter');
Would return the ending date of the 4th quarter of the year "2019".
moment().endOf('quarter');
Would return the ending date of the current quarter of current year.
Given that you haven't provided any criteria for how to determine what quarter "*we are currently in", an algorithm can be suggested that you must then adapt to whatever criteria you need. e.g.
// For the US Government fiscal year
// Oct-Dec = 1
// Jan-Mar = 2
// Apr-Jun = 3
// Jul-Sep = 4
function getQuarter(d) {
d = d || new Date();
var m = Math.floor(d.getMonth()/3) + 2;
return m > 4? m - 4 : m;
}
As a runnable snippet and including the year:
function getQuarter(d) {
d = d || new Date();
var m = Math.floor(d.getMonth() / 3) + 2;
m -= m > 4 ? 4 : 0;
var y = d.getFullYear() + (m == 1? 1 : 0);
return [y,m];
}
console.log(`The current US fiscal quarter is ${getQuarter().join('Q')}`);
console.log(`1 July 2018 is ${getQuarter(new Date(2018,6,1)).join('Q')}`);
You can then adapt that to the various financial or calendar quarters as appropriate. You can also do:
function getQuarter(d) {
d = d || new Date(); // If no date supplied, use today
var q = [4,1,2,3];
return q[Math.floor(d.getMonth() / 3)];
}
Then use different q
arrays depending on the definition of quarter required.
The following gets the days remaining in a quarter if they start on 1 Jan, Apr, Jul and Oct, It's tested in various browsers, including IE 6 (though since it uses basic ECMAScript it should work everywhere):
function daysLeftInQuarter(d) {
d = d || new Date();
var qEnd = new Date(d);
qEnd.setMonth(qEnd.getMonth() + 3 - qEnd.getMonth() % 3, 0);
return Math.floor((qEnd - d) / 8.64e7);
}