【问题标题】:Getting the correct date from an HTML date picker using javascript [duplicate]使用javascript从HTML日期选择器中获取正确的日期[重复]
【发布时间】: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


【解决方案1】:

输入日期值属性

  1. 为日期字段设置日期:getElementById("myDate")。价值 = "2014-02-09";
  2. 获取日期字段的日期:var x = document. getElementById(“我的日期”)。价值;
  3. 显示 defaultValue 和 值属性:getElementById("myDate"); var defaultVal = x。 默认值; var currentVal = x。

【讨论】:

    猜你喜欢
    • 2012-01-14
    • 2013-09-04
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    相关资源
    最近更新 更多