给定一个输入元素:

<input type="date" />

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


当前回答

HTML

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

JQuery

$(document).ready(function() {
    var date = new Date();

    var day = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear();

    if (month < 10) month = "0" + month;
    if (day < 10) day = "0" + day;

    var today = year + "-" + month + "-" + day +"T00:00";       
    $("#theDate").attr("value", today);
});

demo

如果你不想使用jQuery,你可以这样做

JS

var date = new Date();

var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();

if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var today = year + "-" + month + "-" + day;       
document.getElementById("theDate").value = today;

demo

TS

const date = new Date()
const year = date.getFullYear()

let month: number | string = date.getMonth() + 1
let day: number | string = date.getDate()

if (month < 10) month = '0' + month
if (day < 10) day = '0' + day

const today = `${year}-${month}-${day}`    
document.getElementById("theDate").value = today;

其他回答

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

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”);”? > >

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

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

这就是我在我的代码中所做的,我刚刚测试过,它工作得很好,输入类型="date"不支持自动设置curdate,所以我用来克服这个限制的方法是使用PHP代码一个简单的代码,像这样。

<html>
<head></head>
    <body>
        <form ...>
            <?php
                echo "<label for='submission_date'>Data de submissão</label>";
                echo "<input type='date' name='submission_date' min='2012-01-01' value='" . date('Y-m-d') . "' required/>";
            ?>
        </form>
    </body>
</html>

希望能有所帮助!

谢谢你,彼得,现在我改代码了。

<input type='date' id='d1' name='d1'>

<script type="text/javascript">
var d1 = new Date();
var y1= d1.getFullYear();
var m1 = d1.getMonth()+1;
if(m1<10)
    m1="0"+m1;
var dt1 = d1.getDate();
if(dt1<10)
dt1 = "0"+dt1;
var d2 = y1+"-"+m1+"-"+dt1;
document.getElementById('d1').value=d2;
</script>

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