给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
给定一个输入元素:
<input type="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) %>" />
干杯!
这在一行JS中是可能的。
HTML:
<input type="date" id="theDate">
JS:
document.getElementById('theDate').value = new Date().toISOString().substring(0, 10);
. getelementbyid(“theDate”)。value = new Date(). toisostring()。substring (0, 10); <input type="date" id="theDate">
使用input:date元素的. defaultvalue属性将日期的默认值设置为今天的日期。
<input type="date" id="date"/>
window.onload = function loadDate() {
let date = new Date(),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
const todayDate = `${year}-${month}-${day}`;
document.getElementById("date").defaultValue = todayDate;
};
loadDate();
或者在窗口加载上使它成为IIFE/self-called函数
window.onload = (function loadDate() {
let date = new Date(),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
const todayDate = `${year}-${month}-${day}`;
document.getElementById("date").defaultValue = todayDate;
})();
与使用value属性设置日期不同,使用defaultValue属性提供了动态优势。
另外,注意日期格式必须匹配,因此我使用todayDate的格式为:
年-月-日
我相信这回答了你的问题,除了你想设置一个静态的开始和结束日期。要做到这一点,请遵循以下Mozilla的示例:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date >
使用moment.js在2行中解决这个问题, html5日期输入类型只接受“YYYY-MM-DD”这种格式。我用这种方法解决问题。
var today = moment().format('YYYY-MM-DD');
$('#datePicker').val(today);
这是解决这个问题最简单的方法。
您可以生成正确格式的日期,如下所示:
const date = new Date().toLocaleDateString('en-CA')
然后把它赋值给输入元素。如果你使用vue.js,你可以这样做:
<input type="date" :value="date">