给定一个输入元素:

<input type="date" />

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


当前回答

由于日期类型只接受“yyyy-MM-dd”格式,因此需要相应地格式化日期值。

这是它的解,

var d = new Date();
var month = d.getMonth();
var month_actual = month + 1;

if (month_actual < 10) {
  month_actual = "0"+month_actual; 
  }

var day_val = d.getDate();
if (day_val < 10) {
  day_val = "0"+day_val; 
  }

document.getElementById("datepicker_id").value = d.getFullYear()+"-"+ month_actual +"-"+day_val;

其他回答

这依赖于PHP:

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

如果你需要填写输入日期时间,你可以使用这个:

<input type="datetime-local" name="datetime" 
       value="<?php echo date('Y-m-d').'T'.date('H:i'); ?>" />

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

干杯!

如果使用PHP,请遵循标准的Y-m-d格式

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

您可以生成正确格式的日期,如下所示:

const date = new Date().toLocaleDateString('en-CA')

然后把它赋值给输入元素。如果你使用vue.js,你可以这样做:

<input type="date" :value="date">