请求实现两个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
相关产品推荐
相关产品推荐

