给定一个输入元素:

<input type="date" />

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


当前回答

现在,我们不应该再使用moment.js,而是使用day.js来处理这个问题,而且没有任何副作用。js很棒,但它并没有向前推进,它相对较大,但非常有用。js具有足够好的特性,足以成为未来几年使用的新候选。

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

其他回答

您可以生成正确格式的日期,如下所示:

const date = new Date().toLocaleDateString('en-CA')

然后把它赋值给输入元素。如果你使用vue.js,你可以这样做:

<input type="date" :value="date">

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

我测试的最简单的工作版本:

< script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> <input type="date" id="date" name="date"> < >脚本 $(" #日期”)。瓦尔(新日期().toJSON () .slice (0, 10)); > < /脚本

这依赖于PHP:

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

这是服务器端真正需要做的事情,因为每个用户的本地时间格式不同,更不用说每个浏览器的行为不同了。

Html日期输入的值应该是这样的格式:yyyy-mm-dd,否则它不会显示一个值。

Asp classic或vbscript:

current_year = DatePart("yyyy",date) 
current_month = DatePart("m",date) 
current_day = DatePart("d",date) 

IF current_month < 10 THEN
current_month = "0"&current_month
END IF
IF current_day < 10 THEN
current_day = "0"&current_day
END IF

get_date = current_year&"-"&current_month&"-"&current_day
Response.Write get_date

今日内容:2019-02-08

然后在你的html中: <input type="date" value="<% =get_date %>"

PHP

就用这个吧: <input type="date" value="<? "=日期(“Y-m-d”);”? > >