Get current quarter in year with javascript

后端 未结 9 1064
有刺的猬
有刺的猬 2020-12-13 02:10

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

9条回答
  •  一个人的身影
    2020-12-13 03:09

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

提交回复
热议问题