给定一个输入元素:

<input type="date" />

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


当前回答

new Date().getFullYear()+"-"+ ((parseInt(new Date().getMonth())+1+100)+"").substring(1)

其他回答

未来证明的解决方案,也是.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,而是使用day.js来处理这个问题,而且没有任何副作用。js很棒,但它并没有向前推进,它相对较大,但非常有用。js具有足够好的特性,足以成为未来几年使用的新候选。

let now = dayjs(); /* same as now = dayjs(new Date()); */

来匹配原始查询。

date.value = new Date().toJSON().split('T')[0] <输入类型=“日期” id=“日期”/>

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

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

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