与任何 HTML 输入字段一样,浏览器会将日期元素留空,除非在 value
属性中指定了默认值。不幸的是,HTML5 没有提供在 HTMLInputElement.prototype.value
中指定 'today'
的方法。
相反,必须明确提供 RFC3339 格式的日期 (YYYY-MM-DD
)。例如:
element.value = "2011-09-29"
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();
local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
进行调整(最终得到的答案)。
valueAsDate
(排除了 IE、Firefox、也许 Safari,基本上除了 Chrome、Opera、Edge 和一些移动浏览器之外的所有浏览器)。一切都支持我的解决方案使用的 value
属性,即使日期输入回退到不支持的浏览器中的文本输入,其他解决方案也会出错或失败。
input[type=datetime-local]
并将其更改为 slice(0,19)
HTH
使用 HTMLInputElement.prototype.valueAsDate
:
document.getElementById('datePicker').valueAsDate = new Date();
valueAsDate
。 html.spec.whatwg.org/multipage/forms.html#dom-input-valueasdate
valueAsDate
设置为 new Date()
,则字段值将设置为 2018-03-28。请参阅austinfrance.wordpress.com/2012/07/09/…
这依赖于 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 填充默认值,如下所示:
$(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,请遵循标准 Ymd 格式
<input type="date" value="<?php echo date("Y-m-d"); ?>">
在 HTML5 中,没有办法将日期字段的默认值设置为今天的日期吗?如其他答案所示,可以使用 JavaScript 设置该值,如果您希望根据加载页面时用户的当前日期设置默认值,这通常是最好的方法。
HTML5 为 input type=date
元素定义了 valueAsDate
属性,使用它,您可以直接从由 new Date()
创建的对象设置初始值。但是,例如 IE 10 不知道该属性。 (它也缺乏对 input type=date
的真正支持,但这是一个不同的问题。)
因此,实际上您需要设置 value
属性,并且它必须采用符合 ISO 8601 的表示法。现在这可以很容易地完成,因为我们可以预期当前使用的浏览器支持 toISOString
方法:
<input type=date id=e>
<script>
document.getElementById('e').value = new Date().toISOString().substring(0, 10);
</script>
= new Date().toISOString().split('T')[0];
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;
如果您在浏览器中执行与日期和时间相关的任何操作,您希望使用 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>
HTML 代码:
<input type="date" value="2022-01-31">
PHP代码:
<input type="date" value="<?= date('Y-m-d') ?>">
日期格式必须为“yyyy-mm-dd”
Javascript
document.getElementById('date-field').value = new Date().toISOString().slice(0, 10);
jQuery
$('#date-field').val(new Date().toISOString().slice(0, 10));
另外的选择
如果您想自定义日期、月份和年份,只需根据您的意愿执行 sum 或 sub 😎 因为月份从 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 );
}
应用今日功能
document.getElementById('date-field').value = today();
$('#date-field').val(today());
使用moment.js分两行解决这个问题,html5日期输入类型只接受“YYYY-MM-DD”这种格式。我这样解决我的问题。
var today = moment().format('YYYY-MM-DD');
$('#datePicker').val(today);
这是解决此问题的最简单方法。
我测试过的最简单的工作版本:
非常简单,只需使用 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>
两个最佳答案都不正确。
一个使用纯 JavaScript 的简短单行代码,考虑本地时区并且不需要定义额外的函数:
常量元素 = document.getElementById('date-input'); element.valueAsNumber = Date.now()-(new Date()).getTimezoneOffset()*60000; <输入ID='日期输入'类型='日期'>
这以毫秒为单位(自纪元以来)获取当前日期时间,并以毫秒为单位应用时区偏移量(分钟 * 每毫秒 60k 分钟)。
您可以使用 element.valueAsDate
设置日期,但是您需要额外调用 Date()
构造函数。
如果您需要填写输入日期时间,您可以使用:
<input type="datetime-local" name="datetime"
value="<?php echo date('Y-m-d').'T'.date('H:i'); ?>" />
对于 NodeJS(使用 SWIG 模板表达):
<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
value
还是 valueAsDate
?不过看起来不错。
这就是我在我的代码中所做的,我刚刚测试过它工作正常,输入 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>
希望能帮助到你!
这是您真正需要在服务器端执行的操作,因为每个用户的本地时间格式不同,更不用说每个浏览器的行为不同了。
Html 日期输入值应采用以下格式:yyyy-mm-dd 否则不会显示值。
ASP 经典,或 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"); ?>">
即使经过这么长时间,它也可能对某人有所帮助。这是简单的 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" />
未来证明解决方案,也是 .split("T")[0]
的替代方案,它不会在内存中创建字符串数组,将使用 String.slice()
,如下所示:
new Date().toISOString().slice(0, -14);
这里给出的很多答案,例如 slice(0, 10)
、substring(0, 10)
等将来都会失败。
他们使用返回 Date.toISOString()
的 Date.toJSON()
:
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().slice(0, -14);
通过 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)
一个简单的解决方案:
<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);
这将以与 ISO 中相同的 YYYY-MM-DD 格式返回,但以您的本地时间而不是 UTC 格式返回。
function getToday() {
return new Date().toLocaleDateString('en-CA', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
}
如果您使用的是 ruby,您可以使用它来将默认值设置为今天的日期和时间:
<input type="datetime-local" name="time" value="<%= Time.now.strftime('%Y-%m-%dT%H:%M') %>" />
由于日期类型只接受格式“yyyy-MM-dd”,因此您需要相应地格式化日期值。
这是解决方案,
var d = new Date();
var month = d.getMonth();
var month_actual = month + 1;
if (month_actual < 10) {
month_actual = "0"+month_actual;
}
var day_val = d.getDate();
if (day_val < 10) {
day_val = "0"+day_val;
}
document.getElementById("datepicker_id").value = d.getFullYear()+"-"+ month_actual +"-"+day_val;
DateTime.now.strftime("%Y-%m-%d")
date('Y-m-d')
因为它需要前导零?myDate.toLocaleDateString('en-CA')
可以解决问题