如何调整JS代码处理上月月末日期显示异常问题?
解决方案
问题根源
当前代码直接对getDate()返回的日期数值做减法,未处理跨月场景,导致月初时出现无效日期值(如0、负数)。正确做法是通过Date对象的setDate()方法计算前N天的日期,该方法会自动处理月份、年份的变更。
修复后的代码
1. 修正月份名称拼写
原代码中部分葡萄牙语月份拼写错误,需修正:
April→AbrilAugosto→AgostoOutobro→Outubro
2. 可复用日期处理代码
// 葡萄牙语月份名称(已修正拼写) const months = [ "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro" ]; // 获取指定天数前的日期对象 function getPreviousDate(daysAgo) { const date = new Date(); date.setDate(date.getDate() - daysAgo); return date; } // 生成促销日期字符串(支持跨月/跨年场景) function generatePromoDates() { // 获取三个目标日期:当前日期、前1天、前2天 const today = new Date(); const yesterday = getPreviousDate(1); const dayBeforeYesterday = getPreviousDate(2); // 提取各日期的日、月、年 const dToday = today.getDate(); const dYesterday = yesterday.getDate(); const dDayBefore = dayBeforeYesterday.getDate(); const mToday = today.getMonth(); const mYesterday = yesterday.getMonth(); const mDayBefore = dayBeforeYesterday.getMonth(); const yToday = today.getFullYear(); // 场景1:三个日期同属当月同年 if (mDayBefore === mToday) { return `${dDayBefore}, ${dYesterday} e ${dToday} de ${months[mToday]} de ${yToday}`; } // 场景2:前两天为上月、当天为当月(同年) else if (mDayBefore === mYesterday && mYesterday === mToday - 1) { return `${dDayBefore}, ${dYesterday} e ${dToday} de ${months[mToday]} de ${yToday}`; } // 场景3:跨年度(如1月1日,前两天为去年12月) else if (mToday === 0 && mDayBefore === 11) { return `${dDayBefore}, ${dYesterday} e ${dToday} de ${months[mToday]} de ${yToday}`; } // 其他复杂跨月场景(可按需扩展) else { return `${dDayBefore} de ${months[mDayBefore]} de ${dayBeforeYesterday.getFullYear()}, ${dYesterday} de ${months[mYesterday]} de ${yesterday.getFullYear()} e ${dToday} de ${months[mToday]} de ${yToday}`; } } // 页面加载后填充日期 document.addEventListener('DOMContentLoaded', function() { const promoText = generatePromoDates(); document.getElementById("diaspromocao1").textContent = promoText; document.getElementById("diaspromocao2").textContent = promoText; });
3. HTML代码保持不变
<span id="diaspromocao1"></span> <span id="diaspromocao2"></span>
效果说明
- 非月初日期(如6月5日):显示
3, 4 e 5 de Junho de 2023,保留原有正确逻辑。 - 6月1日:显示
30, 31 e 1 de Junho de 2023,符合需求中的示例。 - 1月1日:显示
30, 31 e 1 de Janeiro de 2024,自动处理跨年场景。
内容的提问来源于stack exchange,提问作者Virgílio Dornelas
相关产品推荐
相关产品推荐

