How to the Get Current Quarter in the Year with JavaScript?

Sometimes, we want to get the current quarter in the year with JavaScript.

In this article, we’ll look at how to the get current quarter in the year with JavaScript.

Get Current Quarter in the Year with JavaScript

To the get current quarter in the year with JavaScript, we can compute the quarter from the date.

For instance, we write:

const getQuarter = (d = new Date()) => {
  let m = Math.floor(d.getMonth() / 3) + 2;
  m -= m > 4 ? 4 : 0;
  const y = d.getFullYear() + (m === 1 ? 1 : 0);
  return [y, m];
}

console.log(getQuarter(new Date(2021, 8, 8)))

We create the getQuarter function that takes the d date object.

In the function body, we call d.getMonth to get the month.

Then we divide that by 3 and add 2.

Next, we shift the m quarter by 4 to get m to be between 1 and 4.

Then we compute the y year by using the d.getFullYear method to get the 4 digit year number.

And then we return 1 or 0 depending on whether m is 1 or not to shift the year according to the definition of the quarter.

The function assumes:

  • Oct-Dec = 1
  • Jan-Mar = 2
  • Apr-Jun = 3
  • Jul-Sep = 4

Then we return y and m in an array.

Therefore, the console log should log [2021, 4] since September is in the 4th quarter.

Conclusion

To the get current quarter in the year with JavaScript, we can compute the quarter from the date.