Get current quarter in year with javascript

后端 未结 9 1058
有刺的猬
有刺的猬 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 02:43

    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.

提交回复
热议问题