给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
当前回答
未来证明的解决方案,也是.split("T")[0]的替代方案,它不会在内存中创建字符串数组,将使用string .slice(),如下所示:
new Date().toISOString().slice(0, -14);
这里给出的很多答案,比如slice(0,10), substring(0,10)等,将来都将失败。 他们使用Date.toJSON()返回Date.toISOString():
toISOString()方法返回一个简化扩展ISO格式(ISO 8601)的字符串,它总是24或27个字符长(YYYY-MM-DDTHH:mm:ss)。sssZ或±YYYYYY-MM-DDTHH:mm:ss。分别为sssZ)。时区始终是零UTC偏移量,由后缀“Z”表示。
一旦年份变成5位数,这些答案就会失败。
datePickerId。value = new Date(). toisostring()。片(0,-14); <input type="date" id="datePickerId" />
其他回答
与任何HTML输入字段一样,浏览器将date元素保留为空,除非在value属性中指定了默认值。不幸的是,HTML5没有提供在htmlputelelement .prototype.value中指定“today”的方法。
相反,必须显式提供RFC3339格式的日期(YYYY-MM-DD)。例如:
element.value = "2011-09-29"
这里有一个简单的方法来做到这一点与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;
HTML:
<input type="date" value="2022-01-31">
PHP:
<input type="date" value="<?= date('Y-m-d') ?>">
日期格式必须为“yyyy-mm-dd”
使用input:date元素的. defaultvalue属性将日期的默认值设置为今天的日期。
<input type="date" id="date"/>
window.onload = function loadDate() {
let date = new Date(),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
const todayDate = `${year}-${month}-${day}`;
document.getElementById("date").defaultValue = todayDate;
};
loadDate();
或者在窗口加载上使它成为IIFE/self-called函数
window.onload = (function loadDate() {
let date = new Date(),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
const todayDate = `${year}-${month}-${day}`;
document.getElementById("date").defaultValue = todayDate;
})();
与使用value属性设置日期不同,使用defaultValue属性提供了动态优势。
另外,注意日期格式必须匹配,因此我使用todayDate的格式为:
年-月-日
我相信这回答了你的问题,除了你想设置一个静态的开始和结束日期。要做到这一点,请遵循以下Mozilla的示例:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date >
这是服务器端真正需要做的事情,因为每个用户的本地时间格式不同,更不用说每个浏览器的行为不同了。
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"¤t_month
END IF
IF current_day < 10 THEN
current_day = "0"¤t_day
END IF
get_date = current_year&"-"¤t_month&"-"¤t_day
Response.Write get_date
今日内容:2019-02-08
然后在你的html中: <input type="date" value="<% =get_date %>"
PHP
就用这个吧: <input type="date" value="<? "=日期(“Y-m-d”);”? > >