给定一个输入元素:

<input type="date" />

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


当前回答

上面两个答案都不正确。

一个简短的单行代码,使用纯JavaScript,考虑本地时区,不需要定义额外的函数:

const element = document.getElementById('date-input'); 元素。valueAsNumber = Date.now()-(new Date()).getTimezoneOffset()*60000; <input id='date-input' type='date'>

这将获得以毫秒为单位的当前datetime(从epoch开始),并应用以毫秒为单位的时区偏移量(分钟* 60k分钟每毫秒)。

您可以使用元素设置日期。valueAsDate,但是你需要额外调用Date()构造函数。

其他回答

new Date().getFullYear()+"-"+ ((parseInt(new Date().getMonth())+1+100)+"").substring(1)

HTML:

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

PHP:

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

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

对于那些使用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) %>" />

干杯!

一个简单的解决方案:

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

未来证明的解决方案,也是.split("T")[0]的替代方案,它不会在内存中创建字符串数组,将使用string .slice(),如下所示:

new Date().toISOString().slice(0, -14);

这里给出的很多答案,比如slice(0,10), substring(0,10)等,将来都将失败。 他们使用Date.toJSON()返回Date.toISOString():

toISOString()方法返回一个简化扩展ISO格式(ISO 8601)的字符串,它总是24或27个字符长(YYYY-MM-DDTHH:mm:ss)。sssZ或±YYYYYY-MM-DDTHH:mm:ss。分别为sssZ)。时区始终是零UTC偏移量,由后缀“Z”表示。

一旦年份变成5位数,这些答案就会失败。

datePickerId。value = new Date(). toisostring()。片(0,-14); <input type="date" id="datePickerId" />