JavaScript操作Date对象加1天同时变更小时是否为正常现象?
问题结论
该现象属于完全正常的情况,不是代码bug,根源是夏令时切换规则导致的。
原因说明
你使用的是欧洲中部时区,该时区每年3月的最后一个周日会执行夏令时切换:时钟会从凌晨2点拨快1小时直接跳到3点,因此2019年3月31日的凌晨2点这个时间点在当地时区是不存在的。
你测试的代码中给3月30日2点加1天刚好命中切换节点,JS内置的Date对象会自动做时区适配,所以最终显示为3月31日3点,时区偏移也从GMT+1变为GMT+2。
生成日期数组的兼容方案
如果要避免夏令时对日期计算的影响,可以选择以下两种方案:
方案1:使用UTC时间处理(完全规避本地时区影响)
// 生成起止日期间所有日期的数组,包含起止日期 function getDatesBetween(startDate, endDate) { const dates = [] // 统一转换为UTC时间实例计算 let current = new Date(Date.UTC(startDate.getFullYear(), startDate.getMonth(), startDate.getDate())) const end = new Date(Date.UTC(endDate.getFullYear(), endDate.getMonth(), endDate.getDate())) while (current <= end) { dates.push(new Date(current)) current.setUTCDate(current.getUTCDate() + 1) } return dates }
方案2:固定时间为中午12点(避开夏令时切换的凌晨时段)
function getDatesBetween(startDate, endDate) { const dates = [] // 初始化时把时间设为中午12点,夏令时切换不会影响中午时段 let current = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate(), 12, 0, 0) const end = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate(), 12, 0, 0) while (current <= end) { dates.push(new Date(current.getFullYear(), current.getMonth(), current.getDate())) current.setDate(current.getDate() + 1) } return dates }
内容的提问来源于stack exchange,提问作者loriswave
相关产品推荐
相关产品推荐

