'Get current quarter in year with javascript
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?
Solution 1:[1]
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);
}
Solution 2:[2]
Assuming January through March are considered Q1 (some countries/companies separate their financial year from their calendar year), the following code should work:
var today = new Date();
var quarter = Math.floor((today.getMonth() + 3) / 3);
This gives you:
Month getMonth() quarter
--------- ---------- -------
January 0 1
February 1 1
March 2 1
April 3 2
May 4 2
June 5 2
July 6 3
August 7 3
September 8 3
October 9 4
November 10 4
December 11 4
As to how to get the days remaining in the quarter, it's basically figuring out the first day of the next quarter and working out the difference, something like:
var today = new Date();
var quarter = Math.floor((today.getMonth() + 3) / 3);
var nextq;
if (quarter == 4) {
nextq = new Date (today.getFullYear() + 1, 1, 1);
} else {
nextq = new Date (today.getFullYear(), quarter * 3, 1);
}
var millis1 = today.getTime();
var millis2 = nextq.getTime();
var daydiff = (millis2 - millis1) / 1000 / 60 / 60 / 24;
That's untested but the theory is sound. Basically create a date corresponding to the next quarter, convert it and today into milliseconds since the start of the epoch, then the difference is the number of milliseconds.
Divide that by the number of milliseconds in a day and you have the difference in days.
That gives you (at least roughly) number of days left in the quarter. You may need to fine-tune it to ensure all times are set to the same value (00:00:00) so that the difference is in exact days.
It may also be off by one, depending on your actual definition of "days left in the quarter".
But it should be a good starting point.
Solution 3:[3]
if the first solution doesn't work than you can just adjust it to the range you would like
var today = new Date();
var month = now.getMonth();
var quarter;
if (month < 4)
quarter = 1;
else if (month < 7)
quarter = 2;
else if (month < 10)
quarter = 3;
else if (month < 13)
quarter = 4;
Solution 4:[4]
function getQuarter(d) {
return Math.floor(d.getMonth()/3) + 1);
}
EDIT: i left out %4, totally right, thanks Clement
Solution 5:[5]
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.
Solution 6:[6]
Depend on month
var date = new Date();
var quarter = parseInt(date.getMonth() / 3 ) + 1 ;
Depend on Date
var date = new Date();
var firstday = new Date(date.getFullYear(),0,1); // XXXX/01/01
var diff = Math.ceil((date - firstday) / 86400000);
// a quarter is about 365/4
quarter = parseInt( diff / ( 365/ 4 )) + 1
// if today is 2012/01/01, the value of quarter is 1.
Solution 7:[7]
This worked for me!
var d = new Date();
var quarter = Math.ceil(d.getMonth() / 3);
console.log(quarter)
Solution 8:[8]
It's not efficient or readable but it's in oneliner flavour.
(new Date(new Date().getFullYear(), Math.floor((new Date().getMonth() + 3) / 3) * 3, 1) - new Date()) / 86400000
Solution 9:[9]
// Set Period Function
SetPeriod(SelectedVal) {
try {
if (SelectedVal === '0') { return; }
if (SelectedVal != null) {
let yrf: number, mtf: number, dyf: number, yrt: number, mtt: number, dyt: number, dtf: any, dtt: any;
let dat = new Date();
let q = 0;
switch (SelectedVal) {
case '-1': // Not specify
frm = ''; to = '';
return;
case '0': // As specify
break;
case '1': // This Month
yrf = yrt = dat.getUTCFullYear();
mtf = mtt = dat.getUTCMonth();
dyf = 1; dyt = this.getDaysInMonth(mtf, yrf);
break;
case '2': // Last Month
dat.setDate(0); // 0 will result in the last day of the previous month
dat.setDate(1); // 1 will result in the first day of the month
yrf = yrt = dat.getUTCFullYear();
mtf = mtt = dat.getUTCMonth();
dyf = 1; dyt = this.getDaysInMonth(mtf, yrf);
break;
case '3': // This quater
q = Math.ceil((dat.getUTCMonth()) / 3);
// tslint:disable-next-line:no-switch-case-fall-through
case '4': // Last quater
if (q === 0) { q = Math.ceil(dat.getUTCMonth() / 3) - 1; if (q === 0) { q = 1; } }
yrf = yrt = dat.getUTCFullYear();
if (q === 1) {
mtf = 0; mtt = 2;
dyf = 1; dyt = 31;
} else if (q === 2) {
mtf = 3; mtt = 5;
dyf = 1; dyt = 30;
} else if (q === 3) {
mtf = 6; mtt = 8;
dyf = 1; dyt = 30;
} else if (q === 4) {
mtf = 9; mtt = 11;
dyf = 1; dyt = 31;
}
break;
case '6': // Last year
dat = new Date(dat.getUTCFullYear(), 0, 1);
// tslint:disable-next-line:no-switch-case-fall-through
case '5': // This year
yrf = yrt = dat.getUTCFullYear();
mtf = 0; mtt = 11;
dyf = 1; dyt = 31;
break;
}
// Convert to new Date
dtf = new Date(yrf, mtf, dyf);
dtt = new Date(yrt, mtt, dyt);
console.log('dtf', dtf);
console.log('dtt', dtt);
}
} catch (e) {
alert(e);
}
}
// Get Day in Month
getDaysInMonth = (month: number, year: number) => {
return new Date(year, month + 1, 0).getDate();
}
Solution 10:[10]
In my case, quarter depends on the input quarter start date (month, day) and quarter duration (3, 6)
function getCurrentQuarter(startDateString, quarterDuration) {
var startDate = new Date(startDateString)
// default order of months
var months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
let startMonth = startDate.getMonth() + 1
let startMonthIndex = months.indexOf(startMonth)
// rotate months to get start month first
if (startMonthIndex != 0) {
var monthsNew = months.slice(startMonthIndex, months.length)
months = monthsNew.concat(months.slice(0, startMonthIndex))
}
let today = new Date()
let thisMonth = today.getMonth() + 1
let thisMonthIndex = months.indexOf(thisMonth) + 1
// compare with date
let thisDay = today.getDate()
let startDay = startDate.getDate()
if (thisDay < startDay) {
// this is previous month
if (thisMonthIndex == 1) {
thisMonthIndex = 12
} else {
thisMonthIndex = thisMonthIndex - 1
}
}
// find quarter
let thisQuarter = Math.ceil(thisMonthIndex / quarterDuration)
return thisQuarter
}
getCurrentQuarter('2021-03-15', 3)
Solution 11:[11]
Universal, fast performance (no division, no floats), easy modified for other standard
const now = new Date()
const currentMonth = now.getMonth() + 1
const currentQuarter = {
1: 1, // January
2: 1, // February
3: 1, // March
4: 2, // April
5: 2, // May
6: 2, // June
7: 3, // July
8: 3, // August
9: 3, // September
10: 4, // October
11: 4, // November
12: 4, // December
}[currentMonth]
console.log(currentQuarter)
Solution 12:[12]
Here is my take
var todayDate = new Date(new Date().setUTCHours(0, 0, 0, 0));
var currentQuarter = Math.floor(todayDate.getMonth() / 3);
var firstDate = new Date(
new Date(todayDate.getFullYear(), currentQuarter * 3, 1).setUTCHours(0, 0, 0, 0)
);
var endDate = new Date(
new Date(
firstDate.getFullYear(),
firstDate.getMonth() + 3,
0
).setUTCHours(0, 0, 0, 0)
);
console.log(endDate)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow