Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

jquery - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...