给定一个输入元素:

<input type="date" />

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


当前回答

来匹配原始查询。

date.value = new Date().toJSON().split('T')[0] <输入类型=“日期” id=“日期”/>

其他回答

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();

在HTML本身中没有将今天的日期插入到输入字段的默认方法。然而,像任何其他输入字段一样,它将接受一个值。

您可以使用PHP获取今天的日期,并将其输入到表单元素的值字段中。

<?php
    // Fetch the year, month and day
    $year = date(Y);
    $month = date(m);
    $day = date(d);

    // Merge them into a string accepted by the input field
    $date_string = "$year-$month-$day";

    // Send to the browser the input field with the value set with the date string
    echo "<input type='date' value='$date_string' />";
?>

value字段接受YYYY-MM-DD格式作为输入,因此只需创建一个与输入值接受的格式相同的变量$date_string,并用从今天的日期和voilá获取的年、月和日填充它!你有一个预先选择的日期!

希望这对你有所帮助。

编辑:

如果希望输入字段嵌套在HTML而不是PHP中,可以执行以下操作。

<?php
    // Fetch the year, month and day
    $year = date(Y);
    $month = date(m);
    $day = date(d);

    // Merge them into a string accepted by the input field
    $date_string = "$year-$month-$day";
?>
<html>
    <head>...</head>
    <body>
        <form>
            <input type="date" value="<?php print($date_string); ?>" />
        </form>
    </body>
</html>

我意识到这个问题是在很久以前(2年前)被问过的,但我仍然花了一段时间在互联网上找到一个明确的答案,所以这篇文章适用于任何正在寻找答案的人,希望它能极大地帮助每个人:)

另一个编辑:

几乎忘记了,过去对我来说非常痛苦的事情是总是忘记设置默认时区,无论何时在PHP中使用date()函数编写脚本。

语法为date_default_timezone_set(…);。可以在PHP.net上找到相关文档,可以在这里找到要插入函数的支持时区列表。这总是很烦人,因为我在澳大利亚,如果我没有正确设置,一切总是向后推10个小时,因为它默认为UTC+0000,我需要UTC+1000,所以要小心:)

现在,我们不应该再使用moment.js,而是使用day.js来处理这个问题,而且没有任何副作用。js很棒,但它并没有向前推进,它相对较大,但非常有用。js具有足够好的特性,足以成为未来几年使用的新候选。

let now = dayjs(); /* same as now = dayjs(new Date()); */

这将返回与ISO相同的YYYY-MM-DD格式,但是您的本地时间,而不是UTC。

function getToday() {
    return new Date().toLocaleDateString('en-CA', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    });
}

由于没有将值设置为今天日期的默认方法,所以我认为这应该取决于它的应用程序。如果您希望最大限度地让受众了解日期选择器,那么可以使用服务器端脚本(PHP、ASP等)设置默认值。

但是,如果它是用于CMS的管理控制台,并且您知道用户将始终在站点上使用JS或您的站点受信任,那么您可以安全地使用JS填充默认值,根据jlbruno。