给定一个输入元素:
<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
其他回答
这就是我在我的代码中所做的,我刚刚测试过,它工作得很好,输入类型="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>
希望能有所帮助!
由于日期类型只接受“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;
JavaScript Date对象为所需的格式提供了足够的内置支持,以避免手动执行:
添加这个以获得正确的时区支持:
Date.prototype.toDateInputValue = (function() {
var local = new Date(this);
local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
return local.toJSON().slice(0,10);
});
jQuery:
$(document).ready( function() {
$('#datePicker').val(new Date().toDateInputValue());
});
纯JS:
document.getElementById('datePicker').value = new Date().toDateInputValue();
new Date().getFullYear()+"-"+ ((parseInt(new Date().getMonth())+1+100)+"").substring(1)
上面两个答案都不正确。
一个简短的单行代码,使用纯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()构造函数。