给定一个输入元素:

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

其他回答

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

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

element.value = "2011-09-29"

这依赖于PHP:

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

Javascript:

var today = new Date();

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

使用moment.js在2行中解决这个问题, html5日期输入类型只接受“YYYY-MM-DD”这种格式。我用这种方法解决问题。

var today = moment().format('YYYY-MM-DD');
 $('#datePicker').val(today);

这是解决这个问题最简单的方法。

对于那些使用ASP VBScript的人

<%
'Generates date in yyyy-mm-dd format
Function GetFormattedDate(setDate)
strDate = CDate(setDate)
strDay = DatePart("d", strDate)
strMonth = DatePart("m", strDate)
strYear = DatePart("yyyy", strDate)
If strDay < 10 Then
  strDay = "0" & strDay
End If
If strMonth < 10 Then
  strMonth = "0" & strMonth
End If
GetFormattedDate = strYear & "-" & strMonth & "-" & strDay
End Function
%>

然后在body中,元素应该是这样的

<input name="today" type="date" value="<%= GetFormattedDate(now) %>" />

干杯!