给定一个输入元素:
<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”
其他回答
未来证明的解决方案,也是.split("T")[0]的替代方案,它不会在内存中创建字符串数组,将使用string .slice(),如下所示:
new Date().toISOString().slice(0, -14);
这里给出的很多答案,比如slice(0,10), substring(0,10)等,将来都将失败。 他们使用Date.toJSON()返回Date.toISOString():
toISOString()方法返回一个简化扩展ISO格式(ISO 8601)的字符串,它总是24或27个字符长(YYYY-MM-DDTHH:mm:ss)。sssZ或±YYYYYY-MM-DDTHH:mm:ss。分别为sssZ)。时区始终是零UTC偏移量,由后缀“Z”表示。
一旦年份变成5位数,这些答案就会失败。
datePickerId。value = new Date(). toisostring()。片(0,-14); <input type="date" id="datePickerId" />
如果你在浏览器中做任何与日期和时间相关的事情,你想要使用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>
谢谢你,彼得,现在我改代码了。
<input type='date' id='d1' name='d1'>
<script type="text/javascript">
var d1 = new Date();
var y1= d1.getFullYear();
var m1 = d1.getMonth()+1;
if(m1<10)
m1="0"+m1;
var dt1 = d1.getDate();
if(dt1<10)
dt1 = "0"+dt1;
var d2 = y1+"-"+m1+"-"+dt1;
document.getElementById('d1').value=d2;
</script>
这是非常简单的应用下面的代码,使用PHP
<input type="date" value="<?= date('Y-m-d', time()); ?>" />
Date函数将通过Date in time()返回当前日期。
即使过了这么久,这也能帮到别人。这是一个简单的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" />