我有一个Javascript函数,该函数返回当前/上一个/下一个季度的日期范围。例如,对于当前季度,它将返回2019-01-01
和2019-03-31
。由于某些原因,一些同事说他们的日期范围不正确:对于他们,它们返回2018-12-31
和2019-02-27
。我注意到这两个用户都在德国/波兰地区。
这是我的jsFiddle
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getUTCMonth() + 1),
day = '' + d.getUTCDate(),
year = d.getUTCFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
function getDate_FQ(range){
var now = new Date();
switch(range){
case 'Previous FQ':
now.setMonth(now.getMonth()-3);
break;
case 'Next FQ':
now.setMonth(now.getMonth()+3);
break;
case 'Current FQ':
break;
}
var quarter = Math.floor((now.getUTCMonth() / 3));
var firstDate = new Date(now.getUTCFullYear(), quarter * 3, 1);
var endDate = new Date(firstDate.getUTCFullYear(), firstDate.getUTCMonth() + 3, 0);
return([firstDate, endDate])
}
let [first, end] = getDate_FQ('Current FQ')
console.log(formatDate(first), formatDate(end))
一个日期推迟1天,另一个日期推迟1个月零一天又如何呢?
最佳答案
如果要让Date
在每个时区中引用相同的时间,请在UTC
中工作并将代码更改为两行:
var firstDate = new Date(Date.UTC(now.getUTCFullYear(), quarter * 3, 1));
var endDate = new Date(Date.UTC(firstDate.getUTCFullYear(), firstDate.getUTCMonth() + 3, 0));