提问人:Ian Brown 提问时间:8/8/2011 最后编辑:Mateen UlhaqIan Brown 更新时间:8/25/2023 访问量:1385428
如何将输入类型日期的默认值设置为今天?
How to set input type date's default value to today?
答:
与任何 HTML 输入字段一样,除非在属性中指定了默认值,否则浏览器会将 date 元素留空。遗憾的是,HTML5 没有提供在 .value
'today'
HTMLInputElement.prototype.value
相反,必须明确提供RFC3339格式的日期 ()。例如:YYYY-MM-DD
element.value = "2011-09-29"
评论
DateTime.now.strftime("%Y-%m-%d")
date('Y-m-d')
myDate.toLocaleDateString('en-CA')
您可以通过 JavaScript 填充默认值,如下所示:
$(document).ready( function() {
var now = new Date();
var month = (now.getMonth() + 1);
var day = now.getDate();
if (month < 10)
month = "0" + month;
if (day < 10)
day = "0" + day;
var today = now.getFullYear() + '-' + month + '-' + day;
$('#datePicker').val(today);
});
我可能会花一些额外的时间来查看月份和日期是否为个位数,并在它们前面加上额外的零......但这应该给你一个想法。
编辑:添加了对额外零的检查。
评论
这依赖于 PHP:
<input type="date" value="<?php echo date('Y-m-d'); ?>" />
评论
<?php echo date('Y-m-d', strtotime(date('Y/m/d'))); ?>
<?php echo date('Y-m-d'); ?>
JavaScript Date 对象为所需的格式提供了足够的内置支持,以避免手动执行此操作:
添加此内容以获得正确的时区支持:
Date.prototype.toDateInputValue = (function() {
var local = new Date(this);
local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
return local.toJSON().slice(0,10);
});
j查询:
$(document).ready( function() {
$('#datePicker').val(new Date().toDateInputValue());
});
纯 JS:
document.getElementById('datePicker').value = new Date().toDateInputValue();
评论
local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
valueAsDate
value
input[type=datetime-local]
slice(0,19)
很简单,只需使用服务器端语言,如PHP,ASP,JAVA,甚至您可以使用javascript。
这是解决方案
<?php
$timezone = "Asia/Colombo";
date_default_timezone_set($timezone);
$today = date("Y-m-d");
?>
<html>
<body>
<input type="date" value="<?php echo $today; ?>">
</body>
</html>
[HTML全
<input type="date" id="theDate">
JQuery
$(document).ready(function() {
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + "-" + month + "-" + day +"T00:00";
$("#theDate").attr("value", today);
});
演示
如果你不想使用jQuery,你可以做这样的事情
JS公司
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + "-" + month + "-" + day;
document.getElementById("theDate").value = today;
演示
TS系列
const date = new Date()
const year = date.getFullYear()
let month: number | string = date.getMonth() + 1
let day: number | string = date.getDate()
if (month < 10) month = '0' + month
if (day < 10) day = '0' + day
const today = `${year}-${month}-${day}`
document.getElementById("theDate").value = today;
使用 HTMLInputElement.prototype.valueAsDate
:
document.getElementById('datePicker').valueAsDate = new Date();
评论
valueAsDate
valueAsDate
new Date()
在 HTML5 中,没有办法将日期字段的默认值设置为今天的日期?如其他答案所示,可以使用 JavaScript 设置该值,如果您希望在加载页面时根据用户的当前日期设置默认值,这通常是最佳方法。
HTML5 定义了元素的属性,使用它,您可以直接从创建的对象(例如由 .但是,例如 IE 10 不知道该属性。(它也缺乏真正的支持,但这是一个不同的问题。valueAsDate
input type=date
new Date()
input type=date
因此,在实践中,您需要设置属性,并且它必须采用符合 ISO 8601 的表示法。如今,这可以很容易地完成,因为我们可以期望当前使用的浏览器支持该方法:value
toISOString
<input type=date id=e>
<script>
document.getElementById('e').value = new Date().toISOString().substring(0, 10);
</script>
评论
= new Date().toISOString().split('T')[0];
如果您需要填写输入日期时间,您可以使用以下命令:
<input type="datetime-local" name="datetime"
value="<?php echo date('Y-m-d').'T'.date('H:i'); ?>" />
这就是我在代码中所做的,我刚刚测试过,它工作正常,input type=“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>
评论
使用 moment.js 分 2 行解决这个问题, html5 日期输入类型只接受“YYYY-MM-DD”这种格式。我以这种方式解决我的问题。
var today = moment().format('YYYY-MM-DD');
$('#datePicker').val(today);
这是解决此问题的最简单方法。
如果您使用的是 PHP,请遵循标准的 Y-m-d 格式
<input type="date" value="<?php echo date("Y-m-d"); ?>">
评论
来自 Javascript:
var today = new Date();
document.getElementById("theDate").value = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2);
new Date().getFullYear()+"-"+ ((parseInt(new Date().getMonth())+1+100)+"").substring(1)
评论
对于 NodeJS(带有 SWIG 模板的 Express):
<input type="date" id="aDate" name="aDate" class="form-control" value="{{ Date.now() | date("Y-m-d") }}" />
一个简单的解决方案:
<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>
评论
document.querySelector('.set-today').value=new Date().toISOString().substr(0,10);
<input id="datePicker" type="date" />
$(document).ready( function() {
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
$('#datePicker').val(today);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="datePicker" type="date" />
最简单的解决方案似乎忽略了将使用 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
评论
value
valueAsDate
这是您真正需要在服务器端做的事情,因为每个用户的本地时间格式都不同,更不用说每个浏览器的行为都不同了。
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="<?= date("Y-m-d"); ?>">
两个顶级答案都是不正确的。
一个简短的单行代码,使用纯 JavaScript,考虑本地时区,不需要定义额外的函数:
const element = document.getElementById('date-input');
element.valueAsNumber = Date.now()-(new Date()).getTimezoneOffset()*60000;
<input id='date-input' type='date'>
这将获取以毫秒为单位的当前日期时间(自纪元以来),并以毫秒为单位应用时区偏移量(分钟 * 每毫秒 60k 分钟)。
您可以使用 but 设置日期,然后对构造函数进行额外的调用。element.valueAsDate
Date()
Java脚本
document.getElementById('date-field').value = new Date().toISOString().slice(0, 10);
Jquery
$('#date-field').val(new Date().toISOString().slice(0, 10));
另一种选择
如果您想自定义日期、月份和年份,只需根据需要😎进行总和或子 对于月份开始形式 0,这就是为什么需要将 1 与月份相加。
function today() {
let d = new Date();
let currDate = d.getDate();
let currMonth = d.getMonth()+1;
let currYear = d.getFullYear();
return currYear + "-" + ((currMonth<10) ? '0'+currMonth : currMonth )+ "-" + ((currDate<10) ? '0'+currDate : currDate );
}
应用 today 函数
document.getElementById('date-field').value = today();
$('#date-field').val(today());
通过应用以下代码,这非常简单,使用PHP
<input type="date" value="<?= date('Y-m-d', time()); ?>" />
Date 函数将返回当前日期,方法是在 中获取日期。time()
评论
即使经过了这么多时间,它也可能对某人有所帮助。这是简单的 JS 解决方案。
JS公司
let date = new Date();
let today = date.toISOString().substr(0, 10);
//console.log("Today: ", today);//test
document.getElementById("form-container").innerHTML =
'<input type="date" name="myDate" value="' + today + '" >';//inject field
[HTML全
<form id="form-container"></form>
类似的解决方案适用于 Angular,无需任何额外的库来转换日期格式。对于 Angular(由于通用组件代码,代码被缩短):
//so in myComponent.ts
//Import.... @Component...etc...
date: Date = new Date();
today: String; //<- note String
//more const ...
export class MyComponent implements OnInit {
//constructor, etc....
ngOnInit() {
this.today = this.date.toISOString().substr(0, 10);
}
}
//so in component.html
<input type="date" [(ngModel)]="today" />
评论
我测试过的最简单的工作版本:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" id="date" name="date">
<script>
$('#date').val(new Date().toJSON().slice(0,10));
</script>
一个面向未来的解决方案,也是不在内存中创建字符串数组的替代方案,将使用 String.slice(),
如下所示:.split("T")[0]
new Date().toISOString().slice(0, -14);
这里给出的很多答案,比如 ,等等,将来都会失败。
他们使用 Date.toJSON() 返回 Date.toISOString():
slice(0, 10)
substring(0, 10)
该方法以简化的扩展 ISO 格式 (ISO 8601) 返回一个字符串,该字符串的长度始终为 24 或 27 个字符(分别为 或 )。时区始终为零 UTC 偏移量,由后缀“Z”表示。
toISOString()
YYYY-MM-DDTHH:mm:ss.sssZ
±YYYYYY-MM-DDTHH:mm:ss.sssZ
一旦年份变为 5 位数字,这些答案将失败。
datePickerId.value = new Date().toISOString().slice(0, -14);
<input type="date" id="datePickerId" />
HTML格式:
<input type="date" value="2022-01-31">
PHP的:
<input type="date" value="<?= date('Y-m-d') ?>">
日期格式必须为“yyyy-mm-dd”"
这将以与 ISO 相同的 YYYY-MM-DD 格式返回,但以本地时间而不是 UTC 返回。
function getToday() {
return new Date().toLocaleDateString('en-CA', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
}
以匹配原始查询。
date.value = new Date().toJSON().split('T')[0]
<input type="date" id="date"/>
在一行 JS 中是可能的。
HTML格式:
<input type="date" id="theDate">
JS:
document.getElementById('theDate').value = new Date().toISOString().substring(0, 10);
document.getElementById('theDate').value = new Date().toISOString().substring(0, 10);
<input type="date" id="theDate">
评论