给定一个输入元素:

<input type="date" />

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


当前回答

上面两个答案都不正确。

一个简短的单行代码,使用纯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()构造函数。

其他回答

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

希望能有所帮助!

这里有一个简单的方法来做到这一点与javascript。

    var date = new Date();
    var datestring = ('0000' + date.getFullYear()).slice(-4) + '-' + ('00' + (date.getMonth() + 1)).slice(-2) + '-' + ('00' + date.getDate()).slice(-2) + 'T'+  ('00' +  date.getHours()).slice(-2) + ':'+ ('00' + date.getMinutes()).slice(-2) +'Z';
    document.getElementById('MyDateTimeInputElement').value = datestring;

来匹配原始查询。

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

Javascript:

var today = new Date();

document.getElementById("theDate").value = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2);

对于那些使用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) %>" />

干杯!