给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
当前回答
这将返回与ISO相同的YYYY-MM-DD格式,但是您的本地时间,而不是UTC。
function getToday() {
return new Date().toLocaleDateString('en-CA', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
}
其他回答
即使过了这么久,这也能帮到别人。这是一个简单的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:
<input type="date" value="<?php echo date('Y-m-d'); ?>" />
使用HTMLInputElement.prototype.valueAsDate:
document.getElementById('datePicker').valueAsDate = new Date();
在HTML5中,没有办法将日期字段的默认值设置为今天的日期?如其他答案所示,可以使用JavaScript设置该值,如果希望根据页面加载时用户的当前日期设置默认值,这通常是最佳方法。
HTML5为input type=date元素定义了valueAsDate属性,使用它,你可以直接从创建的对象中设置初始值,例如new date()。然而,IE 10不知道这个属性。(它也缺乏对输入type=date的真正支持,但这是另一个问题。)
因此在实践中,您需要设置value属性,并且必须使用ISO 8601符号法。现在这很容易做到,因为我们可以期望当前使用的浏览器支持toISOString方法:
<input type=date id=e>
<script>
document.getElementById('e').value = new Date().toISOString().substring(0, 10);
</script>
对于那些使用ASP VBScript的人
<%
'Generates date in yyyy-mm-dd format
Function GetFormattedDate(setDate)
strDate = CDate(setDate)
strDay = DatePart("d", strDate)
strMonth = DatePart("m", strDate)
strYear = DatePart("yyyy", strDate)
If strDay < 10 Then
strDay = "0" & strDay
End If
If strMonth < 10 Then
strMonth = "0" & strMonth
End If
GetFormattedDate = strYear & "-" & strMonth & "-" & strDay
End Function
%>
然后在body中,元素应该是这样的
<input name="today" type="date" value="<%= GetFormattedDate(now) %>" />
干杯!