给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
当前回答
new Date().getFullYear()+"-"+ ((parseInt(new Date().getMonth())+1+100)+"").substring(1)
其他回答
这将返回与ISO相同的YYYY-MM-DD格式,但是您的本地时间,而不是UTC。
function getToday() {
return new Date().toLocaleDateString('en-CA', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
}
由于日期类型只接受“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;
如果你需要填写输入日期时间,你可以使用这个:
<input type="datetime-local" name="datetime"
value="<?php echo date('Y-m-d').'T'.date('H:i'); ?>" />
最简单的解决方案似乎忽略了将使用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
上面两个答案都不正确。
一个简短的单行代码,使用纯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()构造函数。