给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
当前回答
最简单的解决方案似乎忽略了将使用UTC时间,包括高度赞成的解决方案。下面是一个精简的,ES6,非jquery版本的一对现有的答案:
const today = (function() {
const now = new Date();
const month = (now.getMonth() + 1).toString().padStart(2, '0');
const day = now.getDate().toString().padStart(2, '0');
return `${now.getFullYear()}-${month}-${day}`;
})();
console.log(today); // as of posting this answer: 2019-01-24
其他回答
我也有同样的问题,我用简单的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脚本应该在最后一行代码,或者在输入之后,因为如果你把这个代码放在前面,脚本就找不到你的输入。
对于那些使用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) %>" />
干杯!
上面两个答案都不正确。
一个简短的单行代码,使用纯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()构造函数。
如果你需要填写输入日期时间,你可以使用这个:
<input type="datetime-local" name="datetime"
value="<?php echo date('Y-m-d').'T'.date('H:i'); ?>" />
Javascript:
var today = new Date();
document.getElementById("theDate").value = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2);