使用 javascript 获取当前季度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11981453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:55:23  来源:igfitidea点击:

Get current quarter in year with javascript

javascriptjquerymathdatedatetime

提问by John Doe

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.

我怎样才能使用 javascript 获得我们所在的当前季度?我试图检测我们目前处于哪个季度,例如 2。

EDITAnd how can I count the number of days left in the quarter?

编辑我如何计算本季度剩余的天数?

回答by paxdiablo

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 timesare set to the same value (00:00:00) so that the difference is in exact days.

这为您提供(至少大致)本季度剩余的天数。您可能需要对其进行微调,以确保所有时间都设置为相同的值 (00:00:00),从而使差异精确到天数。

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.

但这应该是一个很好的起点。

回答by RobG

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 qarrays depending on the definition of quarter required.

然后q根据所需的季度定义使用不同的数组。

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):

如果它们从 1 月 1 日、4 月、7 月和 10 月开始,以下将获得一个季度的剩余天数,它在各种浏览器中进行了测试,包括 IE 6(尽管它使用基本的 ECMAScript,因此应该可以在任何地方使用):

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

回答by Tom Prats

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;

回答by Shih-En Chou

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.

回答by Divya

This worked for me!

这对我有用!

var d = new Date();
var quarter = Math.ceil(d.getMonth() / 3);

console.log(quarter)

回答by Wim den Herder

function getQuarter(d) {
  return Math.floor((d.getMonth()/3 % 4) + 1);
}

回答by The Best

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

回答by Matas Vaitkevicius

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