给定一个输入元素:

<input type="date" />

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


当前回答

使用input:date元素的. defaultvalue属性将日期的默认值设置为今天的日期。

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

window.onload = function loadDate() {
    let date = new Date(),
        day = date.getDate(),
        month = date.getMonth() + 1,
        year = date.getFullYear();

    if (month < 10) month = "0" + month;
    if (day < 10) day = "0" + day;

    const todayDate = `${year}-${month}-${day}`;

    document.getElementById("date").defaultValue = todayDate;
};

loadDate();

或者在窗口加载上使它成为IIFE/self-called函数

window.onload = (function loadDate() {
    let date = new Date(),
        day = date.getDate(),
        month = date.getMonth() + 1,
        year = date.getFullYear();

    if (month < 10) month = "0" + month;
    if (day < 10) day = "0" + day;

    const todayDate = `${year}-${month}-${day}`;

    document.getElementById("date").defaultValue = todayDate;
})();

与使用value属性设置日期不同,使用defaultValue属性提供了动态优势。

另外,注意日期格式必须匹配,因此我使用todayDate的格式为:

年-月-日

我相信这回答了你的问题,除了你想设置一个静态的开始和结束日期。要做到这一点,请遵循以下Mozilla的示例:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date >

其他回答

与任何HTML输入字段一样,浏览器将date元素保留为空,除非在value属性中指定了默认值。不幸的是,HTML5没有提供在htmlputelelement .prototype.value中指定“today”的方法。

相反,必须显式提供RFC3339格式的日期(YYYY-MM-DD)。例如:

element.value = "2011-09-29"

HTML:

<input type="date" value="2022-01-31">

PHP:

<input type="date" value="<?= date('Y-m-d') ?>">

日期格式必须为“yyyy-mm-dd”

这依赖于PHP:

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

一个简单的解决方案:

<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>

这里有一个简单的方法来做到这一点与javascript。

    var date = new Date();
    var datestring = ('0000' + date.getFullYear()).slice(-4) + '-' + ('00' + (date.getMonth() + 1)).slice(-2) + '-' + ('00' + date.getDate()).slice(-2) + 'T'+  ('00' +  date.getHours()).slice(-2) + ':'+ ('00' + date.getMinutes()).slice(-2) +'Z';
    document.getElementById('MyDateTimeInputElement').value = datestring;