给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
当前回答
如果你在浏览器中做任何与日期和时间相关的事情,你想要使用Moment.js:
moment().format('YYYY-MM-DD');
Moment()返回一个表示当前日期和时间的对象。然后调用它的.format()方法以根据指定的格式获得字符串表示形式。在本例中,是YYYY-MM-DD。
完整的例子:
<input id="today" type="date">
<script>
document.getElementById('today').value = moment().format('YYYY-MM-DD');
</script>
其他回答
new Date().getFullYear()+"-"+ ((parseInt(new Date().getMonth())+1+100)+"").substring(1)
使用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 >
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();
只是为了一些新的/不同的东西-你可以使用php来做它。
<?php
$todayDate = date('Y-m-d', strtotime('today'));
echo "<input type='date' value='$todayDate' />";
?>
上面两个答案都不正确。
一个简短的单行代码,使用纯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()构造函数。