给定一个输入元素:

<input type="date" />

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


当前回答

如果使用PHP,请遵循标准的Y-m-d格式

<input type="date" value="<?php echo date("Y-m-d"); ?>">

其他回答

最简单的解决方案似乎忽略了将使用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

你可以通过JavaScript填充默认值,如下所示:

http://jsfiddle.net/7LXPq/

$(document).ready( function() {
    var now = new Date();
    var month = (now.getMonth() + 1);               
    var day = now.getDate();
    if (month < 10) 
        month = "0" + month;
    if (day < 10) 
        day = "0" + day;
    var today = now.getFullYear() + '-' + month + '-' + day;
    $('#datePicker').val(today);
});

我可能会多花点时间看看月份和日期是否是个位数,并在它们前面加上额外的零……但这应该能给你一个概念。

编辑:增加检查额外的零。

我也有同样的问题,我用简单的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脚本应该在最后一行代码,或者在输入之后,因为如果你把这个代码放在前面,脚本就找不到你的输入。

一个简单的解决方案:

<input class="set-today" type="date">
<script type="text/javascript">
    window.onload= function() {
        document.querySelector('.set-today').value=(new Date()).toISOString().substr(0,10));
    }
</script>

对于NodeJS(带有SWIG模板的Express):

<input type="date" id="aDate" name="aDate" class="form-control" value="{{ Date.now() | date("Y-m-d") }}" />