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

请求实现两个Date Picker字段的指定日期自动填充功能

实现自动填充指定日期的Date Picker

首先修正HTML结构,给输入框添加对应id,让标签与输入框正确关联:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Date Picker</title>
</head>
<body>
    <label for="start-date">Start Date</label>
    <input id="start-date" class="date-picker" type="text">
    <label for="end-date">End Date</label>
    <input id="end-date" class="date-picker" type="text">
</body>
</html>

添加以下JavaScript代码即可实现需求:

// 获取当前年份
const currentYear = new Date().getFullYear();

// 生成起始日期:当前年份的1月1日,格式化为dd/mm/yyyy
const startDate = new Date(currentYear, 0, 1); // JavaScript中月份从0开始,0对应1月
const formattedStartDate = `${String(startDate.getDate()).padStart(2, '0')}/${String(startDate.getMonth() + 1).padStart(2, '0')}/${startDate.getFullYear()}`;

// 生成当前日期,格式化为dd/mm/yyyy
const currentDate = new Date();
const formattedCurrentDate = `${String(currentDate.getDate()).padStart(2, '0')}/${String(currentDate.getMonth() + 1).padStart(2, '0')}/${currentDate.getFullYear()}`;

// 为输入框赋值
document.getElementById('start-date').value = formattedStartDate;
document.getElementById('end-date').value = formattedCurrentDate;

代码说明

  • new Date(currentYear, 0, 1):创建当前年份1月1日的日期对象,注意JavaScript的月份计数从0开始,因此0代表1月。
  • padStart(2, '0'):确保日期、月份始终为两位数字(例如将1转换为01),匹配需求的格式。
  • 通过getElementById定位输入框,将格式化后的日期赋值到对应字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:55:18