给定一个输入元素:

<input type="date" />

有没有办法将日期字段的默认值设置为今天的日期?


当前回答

对于那些使用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) %>" />

干杯!

其他回答

对于NodeJS(带有SWIG模板的Express):

<input type="date" id="aDate" name="aDate" class="form-control" value="{{ Date.now() | date("Y-m-d") }}" />

由于没有将值设置为今天日期的默认方法,所以我认为这应该取决于它的应用程序。如果您希望最大限度地让受众了解日期选择器,那么可以使用服务器端脚本(PHP、ASP等)设置默认值。

但是,如果它是用于CMS的管理控制台,并且您知道用户将始终在站点上使用JS或您的站点受信任,那么您可以安全地使用JS填充默认值,根据jlbruno。

即使过了这么久,这也能帮到别人。这是一个简单的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,JAVA,甚至你可以使用javascript。

这是解决方案

<?php
  $timezone = "Asia/Colombo";
  date_default_timezone_set($timezone);
  $today = date("Y-m-d");
?>
<html>
  <body>
    <input type="date" value="<?php echo $today; ?>">
  </body>
</html>
new Date().getFullYear()+"-"+ ((parseInt(new Date().getMonth())+1+100)+"").substring(1)