You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为搜索功能的日期输入框设置当前日期值?

解决input type="date"默认值设为今日的问题

HTML里的input[type="date"]要求value属性必须是YYYY-MM-DD格式的字符串,静态HTML没法自动获取当前日期,所以得用代码动态生成并赋值,下面是两种可行方案:

方案一:原生JavaScript(静态HTML页面适用)

先给输入框加上ID方便选取,再用JS获取并格式化今日日期,最后赋值:

<input type="date" name="start" id="startDate"/>
<input type="date" name="end" id="endDate"/>

<script>
// 获取当前日期对象
const today = new Date();
// 格式化年、月、日为两位数格式
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需加1补正
const day = String(today.getDate()).padStart(2, '0');
const todayStr = `${year}-${month}-${day}`;

// 给两个日期输入框设置默认值
document.getElementById('startDate').value = todayStr;
document.getElementById('endDate').value = todayStr;
</script>

padStart(2, '0')的作用是确保月份和日期都是两位数(比如把1转成01),完全符合date输入框的格式要求。

方案二:服务端渲染(后端语言生成日期)

如果你的页面是后端渲染的(比如PHP、Node.js、Python等),可以直接在服务端生成今日的YYYY-MM-DD字符串,赋值给value属性:

PHP示例:

<input type="date" name="start" value="<?php echo date('Y-m-d'); ?>"/>
<input type="date" name="end" value="<?php echo date('Y-m-d'); ?>"/>

Node.js(EJS模板)示例:

<input type="date" name="start" value="<%= new Date().toISOString().split('T')[0] %>"/>
<input type="date" name="end" value="<%= new Date().toISOString().split('T')[0] %>"/>

内容的提问来源于stack exchange,提问作者Phatt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 08:35:21