gpt4 book ai didi

javascript 在循环中添加分钟

转载 作者:行者123 更新时间:2023-11-28 13:44:21 25 4
gpt4 key购买 nike

无法弄清楚这一点,从 9:00 到 10:00 一切都是正确的,但随后一切都变得困惑。 10:00 后跳到 11:15,然后跳到 12:30

我只是在日期/时间中添加分钟,以 15 分钟为间隔递增数组,我最多只能添加 60 分钟吗??

function pad(val,max) { 
var str = val.toString();
return str.length < max ? pad("0" + str, max) : str;
}

function cboHrs(){
var now = new Date();
now.setHours(9);
var hrs = [];
for (var i=1;i<36;i++){
var hr = {};
now.setMinutes(i*15);
hr.txt = pad(now.getHours(),2) +':'+pad(now.getMinutes(),2);
hr.val = hr.txt;
hrs.push(hr);
}
return hrs;
}
console.log(cboHrs());

最佳答案

安东尼在我之前解决了实际问题......

After the 5th iteration, you are setting the minutes to become 75 (ie, 5 * 15 = 75) which is an 1 hour and 15 minutes which is why the next value after 10:00 becomes 11:15 - Anthony Forloney

此代码应该可以正确设置时间。

function cboHrs(){
var now = new Date();
var hrs = [];
for (var i=1;i<36;i++){
var hr = {};
// add another hour every 4th iteration
now.setHours(9 + parseInt(i / 4));
// add 15 minutes every iteration, starting back at 0 on the 4th
now.setMinutes((i % 4) * 15);
hr.txt = pad(now.getHours(),2) +':'+pad(now.getMinutes(),2);
hr.val = hr.txt;
hrs.push(hr);
}
return hrs;
}

关于javascript 在循环中添加分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15523142/

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