给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
当前回答
Javascript:
var today = new Date();
document.getElementById("theDate").value = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2);
其他回答
与任何HTML输入字段一样,浏览器将date元素保留为空,除非在value属性中指定了默认值。不幸的是,HTML5没有提供在htmlputelelement .prototype.value中指定“today”的方法。
相反,必须显式提供RFC3339格式的日期(YYYY-MM-DD)。例如:
element.value = "2011-09-29"
使用HTMLInputElement.prototype.valueAsDate:
document.getElementById('datePicker').valueAsDate = new Date();
来匹配原始查询。
date.value = new Date().toJSON().split('T')[0] <输入类型=“日期” id=“日期”/>
对于那些使用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) %>" />
干杯!
如果你在浏览器中做任何与日期和时间相关的事情,你想要使用Moment.js:
moment().format('YYYY-MM-DD');
Moment()返回一个表示当前日期和时间的对象。然后调用它的.format()方法以根据指定的格式获得字符串表示形式。在本例中,是YYYY-MM-DD。
完整的例子:
<input id="today" type="date">
<script>
document.getElementById('today').value = moment().format('YYYY-MM-DD');
</script>