给定一个输入元素:

<input type="date" />

有没有办法将日期字段的默认值设置为今天的日期?


当前回答

最简单的解决方案似乎忽略了将使用UTC时间,包括高度赞成的解决方案。下面是一个精简的,ES6,非jquery版本的一对现有的答案:

const today = (function() {
    const now = new Date();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    return `${now.getFullYear()}-${month}-${day}`;
})();

console.log(today);  // as of posting this answer: 2019-01-24

其他回答

<input id="datePicker" type="date" />

美元(文档)。Ready (function() { var now = new Date(); var day = ("0" + now.getDate()).slice(-2); var月=(“0”+ (now.getMonth () + 1)) .slice (2); 今天var = now.getFullYear() +“-”+(月)+“-”+(一天); $ (' # datePicker ') .val(今天); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <input id="datePicker" type="date" />

JavaScript Date对象为所需的格式提供了足够的内置支持,以避免手动执行:

添加这个以获得正确的时区支持:

Date.prototype.toDateInputValue = (function() {
    var local = new Date(this);
    local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
    return local.toJSON().slice(0,10);
});

jQuery:

$(document).ready( function() {
    $('#datePicker').val(new Date().toDateInputValue());
});​

纯JS:

document.getElementById('datePicker').value = new Date().toDateInputValue();

我也有同样的问题,我用简单的JS解决了它。输入:

<input type="date" name="dateOrder" id="dateOrder"  required="required">

JS的

<script language="javascript">
document.getElementById('dateOrder').value = "<?php echo date("Y-m-d"); ?>";
</script>

重点:JS脚本应该在最后一行代码,或者在输入之后,因为如果你把这个代码放在前面,脚本就找不到你的输入。

这就是我在我的代码中所做的,我刚刚测试过,它工作得很好,输入类型="date"不支持自动设置curdate,所以我用来克服这个限制的方法是使用PHP代码一个简单的代码,像这样。

<html>
<head></head>
    <body>
        <form ...>
            <?php
                echo "<label for='submission_date'>Data de submissão</label>";
                echo "<input type='date' name='submission_date' min='2012-01-01' value='" . date('Y-m-d') . "' required/>";
            ?>
        </form>
    </body>
</html>

希望能有所帮助!

最简单的解决方案似乎忽略了将使用UTC时间,包括高度赞成的解决方案。下面是一个精简的,ES6,非jquery版本的一对现有的答案:

const today = (function() {
    const now = new Date();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    return `${now.getFullYear()}-${month}-${day}`;
})();

console.log(today);  // as of posting this answer: 2019-01-24