给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
当前回答
在HTML本身中没有将今天的日期插入到输入字段的默认方法。然而,像任何其他输入字段一样,它将接受一个值。
您可以使用PHP获取今天的日期,并将其输入到表单元素的值字段中。
<?php
// Fetch the year, month and day
$year = date(Y);
$month = date(m);
$day = date(d);
// Merge them into a string accepted by the input field
$date_string = "$year-$month-$day";
// Send to the browser the input field with the value set with the date string
echo "<input type='date' value='$date_string' />";
?>
value字段接受YYYY-MM-DD格式作为输入,因此只需创建一个与输入值接受的格式相同的变量$date_string,并用从今天的日期和voilá获取的年、月和日填充它!你有一个预先选择的日期!
希望这对你有所帮助。
编辑:
如果希望输入字段嵌套在HTML而不是PHP中,可以执行以下操作。
<?php
// Fetch the year, month and day
$year = date(Y);
$month = date(m);
$day = date(d);
// Merge them into a string accepted by the input field
$date_string = "$year-$month-$day";
?>
<html>
<head>...</head>
<body>
<form>
<input type="date" value="<?php print($date_string); ?>" />
</form>
</body>
</html>
我意识到这个问题是在很久以前(2年前)被问过的,但我仍然花了一段时间在互联网上找到一个明确的答案,所以这篇文章适用于任何正在寻找答案的人,希望它能极大地帮助每个人:)
另一个编辑:
几乎忘记了,过去对我来说非常痛苦的事情是总是忘记设置默认时区,无论何时在PHP中使用date()函数编写脚本。
语法为date_default_timezone_set(…);。可以在PHP.net上找到相关文档,可以在这里找到要插入函数的支持时区列表。这总是很烦人,因为我在澳大利亚,如果我没有正确设置,一切总是向后推10个小时,因为它默认为UTC+0000,我需要UTC+1000,所以要小心:)
其他回答
如果你需要填写输入日期时间,你可以使用这个:
<input type="datetime-local" name="datetime"
value="<?php echo date('Y-m-d').'T'.date('H:i'); ?>" />
如果使用PHP,请遵循标准的Y-m-d格式
<input type="date" value="<?php echo date("Y-m-d"); ?>">
由于日期类型只接受“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;
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();
$(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);