给定一个输入元素:

<input type="date" />

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


当前回答

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

其他回答

只是为了一些新的/不同的东西-你可以使用php来做它。

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

上面两个答案都不正确。

一个简短的单行代码,使用纯JavaScript,考虑本地时区,不需要定义额外的函数:

const element = document.getElementById('date-input'); 元素。valueAsNumber = Date.now()-(new Date()).getTimezoneOffset()*60000; <input id='date-input' type='date'>

这将获得以毫秒为单位的当前datetime(从epoch开始),并应用以毫秒为单位的时区偏移量(分钟* 60k分钟每毫秒)。

您可以使用元素设置日期。valueAsDate,但是你需要额外调用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"  />

这在一行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">

你可以通过JavaScript填充默认值,如下所示:

http://jsfiddle.net/7LXPq/

$(document).ready( function() {
    var now = new Date();
    var month = (now.getMonth() + 1);               
    var day = now.getDate();
    if (month < 10) 
        month = "0" + month;
    if (day < 10) 
        day = "0" + day;
    var today = now.getFullYear() + '-' + month + '-' + day;
    $('#datePicker').val(today);
});

我可能会多花点时间看看月份和日期是否是个位数,并在它们前面加上额外的零……但这应该能给你一个概念。

编辑:增加检查额外的零。