给定一个输入元素:

<input type="date" />

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


当前回答

这依赖于PHP:

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

其他回答

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

干杯!

HTML

<input type="date" id="theDate">

JQuery

$(document).ready(function() {
    var date = new Date();

    var day = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear();

    if (month < 10) month = "0" + month;
    if (day < 10) day = "0" + day;

    var today = year + "-" + month + "-" + day +"T00:00";       
    $("#theDate").attr("value", today);
});

demo

如果你不想使用jQuery,你可以这样做

JS

var date = new Date();

var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();

if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var today = year + "-" + month + "-" + day;       
document.getElementById("theDate").value = today;

demo

TS

const date = new Date()
const year = date.getFullYear()

let month: number | string = date.getMonth() + 1
let day: number | string = date.getDate()

if (month < 10) month = '0' + month
if (day < 10) day = '0' + day

const today = `${year}-${month}-${day}`    
document.getElementById("theDate").value = today;

我也有同样的问题,我用简单的JS解决了它。输入:

<input type="date" name="dateOrder" id="dateOrder"  required="required">

JS的

<script language="javascript">
document.getElementById('dateOrder').value = "<?php echo date("Y-m-d"); ?>";
</script>

重点:JS脚本应该在最后一行代码,或者在输入之后,因为如果你把这个代码放在前面,脚本就找不到你的输入。

使用HTMLInputElement.prototype.valueAsDate:

document.getElementById('datePicker').valueAsDate = new Date();

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

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