计算日期时间差值时出现NaN问题求助
问题分析与解决方案
你遇到的NaN问题根源是:从datetime-local输入框获取的value是字符串格式(比如2023-08-31T10:39),而非Date对象,直接对字符串做减法运算会得到NaN,导致后续所有计算失效。
修正步骤
- 将输入的字符串转换为
Date实例后再传入时间差计算函数 - 新增日期有效性检查,避免无效输入导致的异常
修正后的代码
JavaScript 部分
function myWorkLog() { let getTimeDifference = function(from, to) { // 检查日期是否有效 if (isNaN(from.getTime()) || isNaN(to.getTime())) { return "请输入有效的日期时间"; } let difMs = (from - to); if (difMs <= 0) { return "0 days, 0 hours, 0 mins"; } else { let difDays = Math.floor(difMs / 86400000); let difHrs = Math.floor((difMs % 86400000) / 3600000); let difMins = Math.round(((difMs % 86400000) % 3600000) / 60000); if (difDays == 0) { return `${difHrs} hours, ${difMins} mins`; } else { return `${difDays} days, ${difHrs} hours, ${difMins} mins`; } } } // 关键修改:将输入字符串转为Date对象 let startTimeStr = document.getElementById("OutageStart").value; let endTimeStr = document.getElementById("OutageEnd").value; let startDate = new Date(startTimeStr); let endDate = new Date(endTimeStr); alert(getTimeDifference(endDate, startDate)); }
HTML 部分(无需修改)
<!DOCTYPE html> <html lang="en-US" xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"> <head> <meta charset="UTF-8"> <meta name="description" content="NE ROC"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="-1" /> <link rel="stylesheet" href="../../stylesNew.css"> <title>Repeat Nodes</title> </head> <body> <!-- Main Content Area --> <div class="row"> <form> <!-- Form tag is only used to allow the Clear button at the bottom to clear the data entry area. --> <!-- Initial and Resolution --> <div class="cell" style="vertical-align: top; padding-top: 10px; "> <div class="row"> <div class="cell">3) Outage Start Date and Time:</div> <div class="cell" style="text-align:left"><input type="datetime-local" id="OutageStart" required></div> </div> <div class="row"> <div class="cell">10a) Outage End Date and Time:</div> <div class="cell" style="text-align:left"><input type="datetime-local" id="OutageEnd" required></div> </div> <div class="row"> <div class="cell"> </div> <div class="cell" id="Email" style="text-align: center;"><input type="button" value="Generate Email" class="SubmitButton" onClick="myWorkLog();" /></div> </div> </div> </form> </div> </body> </html>
额外说明
datetime-local返回的字符串格式是符合ISO标准的YYYY-MM-DDTHH:mm,可以直接被new Date()正确解析为日期对象- 新增的有效性检查可以在用户输入无效日期时给出明确提示,避免无意义的
NaN输出 - 你注释掉的测试代码能正常运行,正是因为直接使用了
Date对象,这也验证了问题确实出在字符串转日期这一步
内容的提问来源于stack exchange,提问作者Kavorka
相关产品推荐
相关产品推荐

