如何调整Angular日历生成函数适配夏令时避免日期偏移错误
问题原因
当前代码基于固定24小时毫秒数DAY_MS累加生成后续日期,夏令时切换当天的实际时长不等于24小时(比如夏令时结束当天会多1小时,总时长25小时),按固定毫秒累加就会出现日期重复、整体偏移的问题。
修复方案
放弃毫秒累加的日期计算逻辑,改用Date对象原生的setDate方法生成日期,原生API会自动处理夏令时、大小月、跨年等边界场景,不需要手动做兼容。
修改后的核心代码如下:
private getCalendarDays(date = new Date()) { const startDate = this.getCalendarStartDay(date); // 用setDate做日期偏移,替代毫秒累加 return this.range(0, 41) .map(num => { const current = new Date(startDate); current.setDate(startDate.getDate() + num); return current; }); } private getCalendarStartDay(date = new Date()) { const [year, month] = [date.getFullYear(), date.getMonth()]; const firstDayOfMonth = new Date(year, month, 1); // 同样用setDate做日期回退 return this.range(1,7) .map(num => { const dt = new Date(firstDayOfMonth); dt.setDate(firstDayOfMonth.getDate() - num); return dt; }) .find(dt => dt.getDay() === 0); } // range方法无需修改 private range(start, end, length = end - start + 1) { return Array.from({ length }, (_, i) => start + i) }
扩展建议:所有涉及日期加减的场景都优先使用
setDate、setMonth、setFullYear这类原生日期方法,不要手动计算毫秒偏移,可完全规避夏令时、月份天数差异这类常见日期计算问题。
内容的提问来源于stack exchange,提问作者Early73
相关产品推荐
相关产品推荐

