给定一个输入元素:
<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>
其他回答
最简单的解决方案似乎忽略了将使用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填充默认值,如下所示:
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);
});
我可能会多花点时间看看月份和日期是否是个位数,并在它们前面加上额外的零……但这应该能给你一个概念。
编辑:增加检查额外的零。
这依赖于PHP:
<input type="date" value="<?php echo date('Y-m-d'); ?>" />
即使过了这么久,这也能帮到别人。这是一个简单的JS解决方案。
JS
let date = new Date();
let today = date.toISOString().substr(0, 10);
//console.log("Today: ", today);//test
document.getElementById("form-container").innerHTML =
'<input type="date" name="myDate" value="' + today + '" >';//inject field
HTML
<form id="form-container"></form>
类似的解决方案也适用于Angular,无需任何额外的库来转换日期格式。对于Angular(由于通用组件代码,代码被缩短了):
//so in myComponent.ts
//Import.... @Component...etc...
date: Date = new Date();
today: String; //<- note String
//more const ...
export class MyComponent implements OnInit {
//constructor, etc....
ngOnInit() {
this.today = this.date.toISOString().substr(0, 10);
}
}
//so in component.html
<input type="date" [(ngModel)]="today" />
由于没有将值设置为今天日期的默认方法,所以我认为这应该取决于它的应用程序。如果您希望最大限度地让受众了解日期选择器,那么可以使用服务器端脚本(PHP、ASP等)设置默认值。
但是,如果它是用于CMS的管理控制台,并且您知道用户将始终在站点上使用JS或您的站点受信任,那么您可以安全地使用JS填充默认值,根据jlbruno。