给定一个输入元素:

<input type="date" />

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


当前回答

这在一行JS中是可能的。

HTML:

<input type="date" id="theDate">

JS:

document.getElementById('theDate').value = new Date().toISOString().substring(0, 10); 

. getelementbyid(“theDate”)。value = new Date(). toisostring()。substring (0, 10); <input type="date" id="theDate">

其他回答

这依赖于PHP:

<input type="date" value="<?php echo date('Y-m-d'); ?>" />

如果你正在使用ruby,你可以使用这个来设置默认值为今天的日期和时间:

<input type="datetime-local" name="time" value="<%= Time.now.strftime('%Y-%m-%dT%H:%M') %>" />

这是非常简单的应用下面的代码,使用PHP

<input type="date" value="<?= date('Y-m-d', time()); ?>" />

Date函数将通过Date in time()返回当前日期。

非常简单,只需使用服务器端语言,如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>

即使过了这么久,这也能帮到别人。这是一个简单的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"  />