将时间输入中的四舍五入时间转换为整小时或半小时



我需要:

XX:01 到 XX:14 向下舍入到 XX:00

XX:15 至 XX:29 四舍五入为 XX:30

XX:31 到 XX:44 向下舍入为 XX:30

XX:45 至 XX:59 四舍五入为 (XX+1(:00

笔记:

  1. 我在代码中只给出了两个案例,最终我有更多的案例
  2. 例如,我在代码中添加了未使用的其他输入,它们无效
  3. 他们必须自动检查是否已输入。

我的代码 html:

<table>
<tr class="day"> 
<td class="forUser1"><input type="time" class="start" id="start_1"></td>
<td class="forUser2"><input type="time" class="end"  id="end_1"></td>
</tr>
<tr class="day">
<td class="forUser1"><input type="time" class="start"  id="start_2"></td>
<td class="forUser2"><input type="time" class="end" id="end_2"></td>
</tr>
</table>

我试过了:

funtion dist (parting) {
dist = parting.split(":");
const distDate = new Date(0, 0, 0, dist[0], dist[1], 0);
(...)
}

document.querySelector('table').addEventListener('change', function(e) {
const classList = e.target.classList
if (classList.contains('start') || classList.contains('end')) {
const tr = e.target.parentNode.parentNode
const [start, end] = [...tr.querySelectorAll('.start,.end')]
(...)
}
})

我认为这次应该分成单独的部分,但老实说,我会采取一切好办法摆脱这种情况

您可以使用querySelectorAll((方法获取所有输入元素,然后为每个change侦听器添加一个侦听器,该侦听器将运行一个名为say,roundFunc的函数,该函数将为您舍入数字,然后将新的舍入数字分配回输入值。

检查并运行以下代码片段或打开此 JSBin 以获取上述方法的实际示例:

const timeInputs = document.querySelectorAll('table input.start, table input.end');
const roundFunc = e => {
let x = e.target.value.split(':');
if (x[1] > 00 && x[1] < 15) {
x[1] = "00";
} else if (x[1] > 44 && x[1] < 60) {
x[0] = x[0] < 10 ? "0" + (parseInt(x[0]) + 1) : parseInt(x[0]) + 1;
x[1] = "00";
}
else {
x[1] = "30";
}
e.target.value = x.join(':');
}
timeInputs.forEach(input => {
input.addEventListener('change', roundFunc);
});
<table>
<tr class="day"> 
<td class="forUser1"><input type="time" class="start" id="start_1"></td>
<td class="forUser2"><input type="time" class="end"  id="end_1"></td>
</tr>
<tr class="day">
<td class="forUser1"><input type="time" class="start"  id="start_2"></td>
<td class="forUser2"><input type="time" class="end" id="end_2"></td>
</tr>
</table>


但是,在提交数据tbh时将其四舍五入会更干净,因为最终用户最终不会因键入时的数字变化而感到困惑。要在准备将数据发送到服务器时对数字进行四舍五入,您可以在提交数据之前roundFunc()运行上述函数。

它可能不是最优雅的,但它似乎有效:

let start = document.querySelector(".start");
start.addEventListener("change", roundTime);
/*
01:00 .. 01:14 -> 01:00
01:15 .. 01:44 -> 01:30
01:45 .. 01:59 -> 02:00
*/
function roundTime(event) {
let time = event.target.value.split(":");
let hours = parseInt(time[0]);
let mins = parseInt(time[1]);
if (mins < 15) {
mins = 0;
} else if (mins < 45) {
mins = 30;
} else if (mins < 60) {
mins = 0;
hours = (hours + 1) % 24;
}
let rounded = [hours.toString().padStart(2, '0'), mins.toString().padStart(2, '0')].join(":");
let result = document.querySelector(".result");
event.target.value = rounded;
}
<input type="time" class="start">

最新更新