gpt4 book ai didi

javascript - 所选季度的最后一天

转载 作者:行者123 更新时间:2023-11-30 17:40:18 25 4
gpt4 key购买 nike

我正在使用以下函数查找所选日期季度的最后一天。现在我只是添加 12*Date.WEEK 但这并不是我想要的。你能看看如何找到季度的最后一天吗?我想在 date2 中有季度的最后一天。

 function catcalc(cal) { 
var date = cal.date;
var time = date.getTime();
var field = document.getElementById("x_Bis");
if (field == cal.params.inputField) {
field = document.getElementById("x_Von");
time -= 12*Date.WEEK; // substract one week
} else {
time += 12*Date.WEEK; // add one week 6*Date.DAY
}
var date2 = new Date(time);
field.value = date2.print("%d.%m.%Y");

我应该保留函数结构和变量名。有两个相互链接的日历字段。用户可以从日历中选择任何日期(不需要时钟时间)。该函数来自 http://cimanet.uoc.edu/logica/v2/lib/jscalendar-1.0/doc/html/reference.html .

最佳答案

2022 年 8 月更新

利用 JS 中下个月的第 0 天是当月的最后一天这一事实。请注意,月份从 0 开始,因此第 3 个月是四月,而四月的第 0 天是 3 月 31 日

const getQ = date => {
const t = new Date(date.getTime()), year = t.getFullYear() // copy
t.setHours(0, 0, 0, 0); // normalise before using
return [3, 6, 9, 12].map(month => new Date(year, month, 0)).find(q=>t<=q)
};


// testing
const output = document.getElementById("output");
let d, q, dates = [new Date(2022, 2, 31, 23, 59), new Date(2022, 4, 31, 23, 59), new Date(2022, 9, 31, 23, 59) ];
output.innerHTML = dates
.map(d => `${getQ(d).toLocaleDateString()} the end of the quarter containing ${d.toLocaleDateString()}`)
.join("<hr/>");
<div id="output"></div>

但实际上是calculation from Balage迄今为止最简单的。

因为他没有打扰,所以在一个函数中

const getQ = date => {
let quarter = Math.floor((date.getMonth() / 3)), startDate = new Date(date.getFullYear(), quarter * 3, 1);
return [startDate, new Date(startDate.getFullYear(), startDate.getMonth() + 3, 0)]
};

const output = document.getElementById("output");
let d, q, dates = [new Date(2022, 2, 31, 23, 59), new Date(2022, 4, 31, 23, 59), new Date(2022, 9, 31, 23, 59) ];
output.innerHTML = dates
.map(d => {
q = getQ(d);
return `${q[0].toLocaleDateString()} is the start and ${q[1].toLocaleDateString()} the end of the quarter containing ${d.toLocaleDateString()}`;
})
.join("<hr/>");
<div id="output"></div>


旧版本

Live Demo

function getQ(date) {
var t=new Date(date.getTime()),year=t.getFullYear() // copy
t.setHours(0,0,0,0); // normalise to not get boundary errors
// note months start at 0 in JS
var q1 = new Date(year,2,31),
q2 = new Date(year,5,30),
q3 = new Date(year,8,30),
q4 = new Date(year,11,31);
if (t<=q1) return q1;
if (t<=q2) return q2;
if (t<=q3) return q3;
if (t<=q4) return q4;
}
getQ(new Date()); // today will return 31st of March

在你的代码中,我猜你可以使用

function catcalc(cal) { 
var date = cal.date;
var field = document.getElementById("x_Bis");
if (field == cal.params.inputField) {
field = document.getElementById("x_Von");
}
var date2 = getQ(date);
field.value = date2.print("%d.%m.%Y");
}

关于javascript - 所选季度的最后一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21220374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com