给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
当前回答
HTML:
<input type="date" value="2022-01-31">
PHP:
<input type="date" value="<?= date('Y-m-d') ?>">
日期格式必须为“yyyy-mm-dd”
其他回答
这依赖于PHP:
<input type="date" value="<?php echo date('Y-m-d'); ?>" />
这里有一个简单的方法来做到这一点与javascript。
var date = new Date();
var datestring = ('0000' + date.getFullYear()).slice(-4) + '-' + ('00' + (date.getMonth() + 1)).slice(-2) + '-' + ('00' + date.getDate()).slice(-2) + 'T'+ ('00' + date.getHours()).slice(-2) + ':'+ ('00' + date.getMinutes()).slice(-2) +'Z';
document.getElementById('MyDateTimeInputElement').value = datestring;
使用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 >
即使过了这么久,这也能帮到别人。这是一个简单的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" />
我测试的最简单的工作版本:
< script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> <input type="date" id="date" name="date"> < >脚本 $(" #日期”)。瓦尔(新日期().toJSON () .slice (0, 10)); > < /脚本