【发布时间】:2021-04-25 16:27:42
【问题描述】:
我正在尝试仅使用 javascript 将日期添加到 HTML 日期选择器。问题是从 HTML 日期选择器返回的日期并不总是正确的。我相信这是因为 HTML 日期选择器不包含时间或时区。如果我使用 HTML datetime-local 输入,一切正常。但我更喜欢只使用输入类型日期。这是我能得到的最接近的。它适用于我测试过的一年中的每一天,除了任何一个月的第一天。在 console.log 中,打开日期是日期选择器的值减去 1 天,默认时间为 20:00:00 GMT -0400。最终目标是,我需要能够从 HTML 日期选择器中为日期添加天数。代码正确添加了天数,但我无法得到正确的开始日期。
echo "
<tr>
<td id='description".$lineID."'>".$row["description"]."</td>
<td id='recieveDate".$lineID."'>".$row["receivedate"]."</td>
<td id='lotnumber".$lineID."'>".$row["lotnumber"]."</td>
<td id='openStability".$lineID."' name='openStability'>".$row["openexpdays"]."</td>
<td><input type='date' id='openDate".$lineID."' name='openDate' onChange='calExpDate(this)'></td>
<td><input type='number' style='width:35px;' id='amount".$lineID."'></td>
<td><input type='date' id='openExpDate".$lineID."' name='openExpDate'></td>
<td><button type='button' id='".$lineID."' value='".$lineID."' onClick='insertRow()'>A</button></td>
</tr>";
<script>
function calExpDate(x) {
var rowIndex = x.parentNode.parentNode.rowIndex;
var stability = parseInt(supplyTable.rows[rowIndex].cells[3].innerHTML);
rowIndex = rowIndex - 1;
var openDate = new Date(document.getElementById('openDate' + rowIndex).value);
console.log("Open Date: " + openDate);
openDate.setDate(openDate.getUTCDate());
console.log("Open Date UTC: " + openDate);
var expDate = new Date(openDate.getFullYear(),openDate.getMonth(),openDate.getDate() + stability);
document.getElementById('openExpDate' + rowIndex).valueAsDate = expDate;
console.log('Exp Date: ' + expDate);
}
</script>
【问题讨论】:
-
发布代码作为可运行的 sn-p,减少到演示问题所需的最低限度。鉴于结果是 -0400(这可能是您的本地时区偏移量),那么您的问题很可能是来自日期输入的值是 YYYY-MM-DD 格式,内置解析器将其解析为 UTC,不是本地的(几年前 TC39 的一个错误决定)。见Why does Date.parse give incorrect results?
-
感谢您的参考。它提供了我需要的确切解决方案。
标签: javascript html date timezone