求助:datetime-local与JS计算结束时间无法得到精确结果
问题:无法精确计算结束时间
我的代码无法计算出输入的精确时长,比如输入起始时间03/08/2023 10:54 AM、时长1小时,预期得到结束时间03/08/2023 11:54 AM,但实际结果不符合预期。
原代码如下:
<label for="start">Start Date:</label> <input type="datetime-local" id="start" onchange="calculateEndDate()"> <label for="hours">Hours:</label> <select id="hours" onchange="calculateEndDate()"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> <label for="end">End Date:</label> <input type="datetime-local" id="end" readonly> <script> function calculateEndDate() { const start = new Date(document.getElementById("start").value); const hours = parseInt(document.getElementById("hours").value); const end = new Date(start.getTime() + hours * 60 * 60 * 1000); document.getElementById("end").value = end.toISOString().slice(0, -8); } </script>
问题原因
原代码使用toISOString()会将时间转换为UTC时区的字符串,而datetime-local输入框基于本地时区解析时间,两者的时区差异导致计算结果偏移,出现时间不准确的情况。
修正后的代码
<label for="start">Start Date:</label> <input type="datetime-local" id="start" onchange="calculateEndDate()"> <label for="hours">Hours:</label> <select id="hours" onchange="calculateEndDate()"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> <label for="end">End Date:</label> <input type="datetime-local" id="end" readonly> <script> function calculateEndDate() { const startInput = document.getElementById("start").value; if (!startInput) return; const start = new Date(startInput); const hours = parseInt(document.getElementById("hours").value); // 在本地时间基础上累加小时 const end = new Date(start); end.setHours(start.getHours() + hours); // 手动格式化为datetime-local要求的格式 const year = end.getFullYear(); const month = String(end.getMonth() + 1).padStart(2, '0'); const day = String(end.getDate()).padStart(2, '0'); const hour = String(end.getHours()).padStart(2, '0'); const minute = String(end.getMinutes()).padStart(2, '0'); document.getElementById("end").value = `${year}-${month}-${day}T${hour}:${minute}`; } </script>
修正说明
- 直接基于本地时间操作:通过
setHours()在原始本地时间上累加时长,避免UTC转换带来的时区偏差 - 手动格式化输出:按照
datetime-local输入框要求的YYYY-MM-DDTHH:mm格式拼接字符串,确保格式完全匹配 - 增加空值判断:未选择起始时间时不执行计算,避免报错
内容的提问来源于stack exchange,提问作者Jonjon Castilleja
相关产品推荐
相关产品推荐

