给定一个输入元素:

<input type="date" />

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


当前回答

这就是我在我的代码中所做的,我刚刚测试过,它工作得很好,输入类型="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>

希望能有所帮助!

其他回答

如果你在浏览器中做任何与日期和时间相关的事情,你想要使用Moment.js:

moment().format('YYYY-MM-DD');

Moment()返回一个表示当前日期和时间的对象。然后调用它的.format()方法以根据指定的格式获得字符串表示形式。在本例中,是YYYY-MM-DD。

完整的例子:

<input id="today" type="date">
<script>
document.getElementById('today').value = moment().format('YYYY-MM-DD');
</script>

一个简单的解决方案:

<input class="set-today" type="date">
<script type="text/javascript">
    window.onload= function() {
        document.querySelector('.set-today').value=(new Date()).toISOString().substr(0,10));
    }
</script>

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

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

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

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

对于那些使用ASP VBScript的人

<%
'Generates date in yyyy-mm-dd format
Function GetFormattedDate(setDate)
strDate = CDate(setDate)
strDay = DatePart("d", strDate)
strMonth = DatePart("m", strDate)
strYear = DatePart("yyyy", strDate)
If strDay < 10 Then
  strDay = "0" & strDay
End If
If strMonth < 10 Then
  strMonth = "0" & strMonth
End If
GetFormattedDate = strYear & "-" & strMonth & "-" & strDay
End Function
%>

然后在body中,元素应该是这样的

<input name="today" type="date" value="<%= GetFormattedDate(now) %>" />

干杯!

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

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