给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
当前回答
一个简单的解决方案:
<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>
其他回答
你可以通过JavaScript填充默认值,如下所示:
http://jsfiddle.net/7LXPq/
$(document).ready( function() {
var now = new Date();
var month = (now.getMonth() + 1);
var day = now.getDate();
if (month < 10)
month = "0" + month;
if (day < 10)
day = "0" + day;
var today = now.getFullYear() + '-' + month + '-' + day;
$('#datePicker').val(today);
});
我可能会多花点时间看看月份和日期是否是个位数,并在它们前面加上额外的零……但这应该能给你一个概念。
编辑:增加检查额外的零。
这就是我在我的代码中所做的,我刚刚测试过,它工作得很好,输入类型="date"不支持自动设置curdate,所以我用来克服这个限制的方法是使用PHP代码一个简单的代码,像这样。
<html>
<head></head>
<body>
<form ...>
<?php
echo "<label for='submission_date'>Data de submissão</label>";
echo "<input type='date' name='submission_date' min='2012-01-01' value='" . date('Y-m-d') . "' required/>";
?>
</form>
</body>
</html>
希望能有所帮助!
这将返回与ISO相同的YYYY-MM-DD格式,但是您的本地时间,而不是UTC。
function getToday() {
return new Date().toLocaleDateString('en-CA', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
}
未来证明的解决方案,也是.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" />
new Date().getFullYear()+"-"+ ((parseInt(new Date().getMonth())+1+100)+"").substring(1)