Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
59
rated 0 times [  60] [ 1]  / answers: 1 / hits: 88176  / 12 Years ago, thu, august 16, 2012, 12:00:00

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 count the number of days left in the quarter?


More From » jquery

 Answers
11

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.



Edit



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

[#83608] Tuesday, August 14, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryonk

Total Points: 161
Total Questions: 116
Total Answers: 107

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
bryonk questions
;