给定一个输入元素:

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

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

你可以通过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);
});

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

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

Javascript:

var today = new Date();

document.getElementById("theDate").value = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2);

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

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