日期选择异常求助:选择日期时误将日识别为月份的问题
问题分析与解决方案
你的问题确实出在Date实例创建环节——原生JavaScript的Date构造函数解析DD.MM.YYYY格式的字符串时,会错误地将日(第一个数字)识别为月份,月(第二个数字)识别为日,导致日期颠倒。比如选择12.01.2023(1月12日),会被解析成2023年12月1日;如果日的数值超过12(比如13.01.2023),Date会因月份不存在解析失败,返回无效日期。
下面给出两种可靠的解决方法:
方案一:手动解析日期字符串,正确构造Date对象
修改nextmonths函数,拆分输入的日期字符串,按年-月-日的正确顺序构造Date对象(注意月份要减1,因为Date的月份取值是0-11):
function nextmonths() { // 获取输入框的日期字符串 const dateStr = document.getElementById("date__start").value; // 按.拆分得到日、月、年 const [day, month, year] = dateStr.split("."); // 正确构造Date对象:月份需减1 const start_multi = new Date(year, month - 1, day); // 后续逻辑保持(若需要计算结束日期可在此处调整,比如加N个月) const next_date = new Date(start_multi); console.log(next_date); // 指定本地化格式,确保输出DD.MM.YYYY const next_date_formatted = next_date.toLocaleDateString('ru-RU'); document.getElementById("date__end").value = next_date_formatted; dateSelected.innerHTML = `С ${start_multi.toLocaleDateString('ru-RU')} по ${next_date_formatted}`; }
方案二:直接使用air-datepicker的API获取选中日期
air-datepicker自带获取选中日期的方法,无需手动解析字符串,更稳定:
首先初始化日期选择器并保存实例,在选中日期时直接获取Date对象:
// 初始化日期选择器,指定显示格式 const startDatepicker = new AirDatepicker('#date__start', { dateFormat: 'dd.MM.yyyy', // 选中日期时自动触发逻辑 onSelect({date}) { nextmonths(date); } }); function nextmonths(selectedDate) { // 直接使用选中的Date对象,避免字符串解析错误 const start_multi = selectedDate; const next_date = new Date(start_multi); console.log(next_date); const next_date_formatted = next_date.toLocaleDateString('ru-RU'); document.getElementById("date__end").value = next_date_formatted; dateSelected.innerHTML = `С ${start_multi.toLocaleDateString('ru-RU')} по ${next_date_formatted}`; }
另外注意:你当前引入的air-datepicker链接是GitHub页面链接,需要替换为直接的资源文件链接,比如:
<link href="https://cdn.jsdelivr.net/npm/air-datepicker@3/dist/air-datepicker.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/air-datepicker@3/dist/air-datepicker.min.js"></script>
内容的提问来源于stack exchange,提问作者Адиль
相关产品推荐
相关产品推荐

