给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
当前回答
$(document).ready(function(){
var date = new Date();
var day = ("0" + date.getDate()).slice(-2); var month = ("0" + (date.getMonth() + 1)).slice(-2);
var today = date.getFullYear()+"-"+(month)+"-"+(day) ;
});
$('#dateid').val(today);
其他回答
如果使用PHP,请遵循标准的Y-m-d格式
<input type="date" value="<?php echo date("Y-m-d"); ?>">
我测试的最简单的工作版本:
< script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> <input type="date" id="date" name="date"> < >脚本 $(" #日期”)。瓦尔(新日期().toJSON () .slice (0, 10)); > < /脚本
对于NodeJS(带有SWIG模板的Express):
<input type="date" id="aDate" name="aDate" class="form-control" value="{{ Date.now() | date("Y-m-d") }}" />
最简单的解决方案似乎忽略了将使用UTC时间,包括高度赞成的解决方案。下面是一个精简的,ES6,非jquery版本的一对现有的答案:
const today = (function() {
const now = new Date();
const month = (now.getMonth() + 1).toString().padStart(2, '0');
const day = now.getDate().toString().padStart(2, '0');
return `${now.getFullYear()}-${month}-${day}`;
})();
console.log(today); // as of posting this answer: 2019-01-24
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();