给定一个输入元素:

<input type="date" />

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


当前回答

如果你正在使用ruby,你可以使用这个来设置默认值为今天的日期和时间:

<input type="datetime-local" name="time" value="<%= Time.now.strftime('%Y-%m-%dT%H:%M') %>" />

其他回答

如果你需要填写输入日期时间,你可以使用这个:

<input type="datetime-local" name="datetime" 
       value="<?php echo date('Y-m-d').'T'.date('H:i'); ?>" />

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

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

与任何HTML输入字段一样,浏览器将date元素保留为空,除非在value属性中指定了默认值。不幸的是,HTML5没有提供在htmlputelelement .prototype.value中指定“today”的方法。

相反,必须显式提供RFC3339格式的日期(YYYY-MM-DD)。例如:

element.value = "2011-09-29"

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

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

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

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

JavaScript Date对象为所需的格式提供了足够的内置支持,以避免手动执行:

添加这个以获得正确的时区支持:

Date.prototype.toDateInputValue = (function() {
    var local = new Date(this);
    local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
    return local.toJSON().slice(0,10);
});

jQuery:

$(document).ready( function() {
    $('#datePicker').val(new Date().toDateInputValue());
});​

纯JS:

document.getElementById('datePicker').value = new Date().toDateInputValue();