给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
给定一个输入元素:
<input type="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”);”? > >
其他回答
这里有一个简单的方法来做到这一点与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;
$(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);
这在一行JS中是可能的。
HTML:
<input type="date" id="theDate">
JS:
document.getElementById('theDate').value = new Date().toISOString().substring(0, 10);
. getelementbyid(“theDate”)。value = new Date(). toisostring()。substring (0, 10); <input type="date" id="theDate">
HTML:
<input type="date" value="2022-01-31">
PHP:
<input type="date" value="<?= date('Y-m-d') ?>">
日期格式必须为“yyyy-mm-dd”
在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,所以要小心:)