Angular中如何实现两个日期相加?当前代码仅能相加年份
问题原因
你当前代码里,parseInt(val1)处理日期字符串(比如"2024-05-20")时,只会读取到第一个非数字字符(-)之前的内容,也就是年份数值,所以两个日期最终只做了年份相加,这就是问题根源。
解决方案
根据「日期相加」的两种常见需求,提供两种实现方式:
方式1:将两个日期的时间戳相加得到新日期
时间戳是从1970年1月1日00:00:00 UTC到目标日期的毫秒数,相加后可转换为新的日期对象:
修改TypeScript代码:
result: string = ''; calculate(val1: string, val2: string) { // 把日期字符串转为Date对象 const date1 = new Date(val1); const date2 = new Date(val2); // 校验日期有效性 if (isNaN(date1.getTime()) || isNaN(date2.getTime())) { this.result = '请输入有效的日期'; return; } // 获取时间戳并相加,再转为新日期 const totalTimestamp = date1.getTime() + date2.getTime(); const newDate = new Date(totalTimestamp); // 格式化输出结果(可按需调整格式) this.result = `相加后的日期:${newDate.toLocaleDateString()}`; }
方式2:分别相加年、月、日数值
如果需求是将两个日期的年、月、日分别累加(比如2024-05-20 + 2023-03-10 = 4047-08-30),可以这样实现:
result: string = ''; calculate(val1: string, val2: string) { // 拆分日期字符串为年、月、日数值 const [year1, month1, day1] = val1.split('-').map(Number); const [year2, month2, day2] = val2.split('-').map(Number); // 校验日期有效性 const date1Valid = !isNaN(year1) && !isNaN(month1) && !isNaN(day1); const date2Valid = !isNaN(year2) && !isNaN(month2) && !isNaN(day2); if (!date1Valid || !date2Valid) { this.result = '请输入有效的日期'; return; } // 计算累加后的年、月、日 let totalYear = year1 + year2; let totalMonth = month1 + month2; let totalDay = day1 + day2; // 处理月份进位(超过12则计入年份) totalYear += Math.floor((totalMonth - 1) / 12); totalMonth = (totalMonth - 1) % 12 + 1; // 处理日期进位(根据当月天数自动调整月、年) const tempDate = new Date(totalYear, totalMonth - 1, totalDay); const finalDate = new Date(totalYear, totalMonth - 1 + tempDate.getMonth(), tempDate.getDate()); this.result = `相加后的日期:${finalDate.toLocaleDateString()}`; }
注意事项
- 日期输入框的
value固定为YYYY-MM-DD格式,可直接拆分或用Date对象解析。 - 必须加入无效日期校验,避免出现
Invalid Date异常。
内容的提问来源于stack exchange,提问作者Jay Mervana
相关产品推荐
相关产品推荐

