gpt4 book ai didi

javascript - 如何计算 Javascript 与 HTML 周表的周差?

转载 作者:行者123 更新时间:2023-12-03 00:57:53 25 4
gpt4 key购买 nike

我正在寻找一种根据另一个周表单元素的输入来填充周表单元素的方法。我对 Javascript 还很陌生。

基本上我需要得到 c1 和 c2 形式之间的周差。然后以相同的周差自动填充 d1 和 d2,但 d1 在 c2 之后一周开始。

示例:

c1 =“2018-W01”

c2 =“2018-W05”

应将 d1 和 d2 值设置为:

d1 =“2018-W06”

d2 =“2018-W10”

    <input type="week" id="c1">
<input type="week" id="c2">
<input type="week" id="d1" readonly>
<input type="week" id="d2" readonly>

<script>
function myFunction() {
var d1 = document.getElementById("c1").value;
var d2 = document.getElementById("c2").value;
var year = d1.substring(0,4); //2018
var day1 = d1.substring(6,); //01
var day2 = d2.substring(6,); //05

var difference = day2 - day1; //5

document.getElementById("d1").value = d1 + difference; // ?
document.getElementById("d2").value = d2 + difference;
</script>

这段代码显然不起作用,但显示了我的想法。这确实会带来两年之间日期重叠的问题。感谢您的帮助!

最佳答案

试试这个..

function myFunction(d1, d2) {

var year1 = parseInt(d1.substring(0, 4)); //2018
var year2 = parseInt(d2.substring(0, 4));
var yearDiff = Math.abs(year1 - year2);
var weeksInYears = 52 * yearDiff;

var day1 = parseInt(d1.substring(6, )); //01
var day2 = parseInt(d2.substring(6, )); //05

var difference = Math.abs(weeksInYears - (day2 - day1)); // handled dates with different years
var week1 = day2 + 1;
var week2 = week1 + difference;
week1 = ((week1 < 10 ? '0' : '') + week1);
week2 = ((week2 < 10 ? '0' : '') + week2)
var res = year1 + "-" + "W" + (week1); // ?
var res1 = year2 + "-" + "W" + (week2);
console.log(res, res1);}

关于javascript - 如何计算 Javascript 与 HTML 周表的周差?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52745374/

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