基于JavaScript的商品发货时间计数器优化与功能拓展需求
商品发货时间计数器实现方案
需求说明
- 下单时效规则:当日10:30前下单,预计1个工作日后发货;超时下单则预计2个工作日后发货(工作日排除周六、周日)
- 示例:2022年10月14日周五10:00下单→发货日期为10月17日(周一);当日12:00下单→发货日期为10月18日(周二)
- 需展示内容:当前日期、10:30截止下单的实时倒计时、预计发货日期
优化后的完整代码
HTML结构
<div class="shipment-info"> <p>当前日期:<span id="today-date"></span></p> <p>剩余下单时间(10:30截止):<span id="countdown-time"></span></p> <p>预计发货日期:<span id="ship-date"></span></p> </div>
JavaScript代码
// 格式化日期为 DD.MM.YYYY 格式 function formatDate(date) { const day = String(date.getDate()).padStart(2, '0'); const month = String(date.getMonth() + 1).padStart(2, '0'); const year = date.getFullYear(); return `${day}.${month}.${year}`; } // 计算排除周末后的目标发货日期 function calculateShipDate(baseDate, daysToAdd) { const targetDate = new Date(baseDate); let count = 0; while (count < daysToAdd) { targetDate.setDate(targetDate.getDate() + 1); // 跳过周日(0)和周六(6) if (targetDate.getDay() !== 0 && targetDate.getDay() !== 6) { count++; } } return targetDate; } // 更新截止下单倒计时 function updateCountdown() { const now = new Date(); const todayCutoff = new Date(now); todayCutoff.setHours(10, 30, 0, 0); let timeLeft; if (now > todayCutoff) { // 已过当日截止时间,计算到次日10:30的剩余时间 const nextCutoff = new Date(todayCutoff); nextCutoff.setDate(nextCutoff.getDate() + 1); timeLeft = nextCutoff - now; } else { // 未过截止时间,计算到当日10:30的剩余时间 timeLeft = todayCutoff - now; } // 转换为时分秒格式 const hours = Math.floor(timeLeft / (1000 * 60 * 60)); const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000); document.getElementById('countdown-time').textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; } // 初始化所有发货信息 function initShipmentInfo() { const now = new Date(); const todayCutoff = new Date(now); todayCutoff.setHours(10, 30, 0, 0); // 显示当前日期 document.getElementById('today-date').textContent = formatDate(now); // 判断需要添加的工作日天数 const daysToAdd = now <= todayCutoff ? 1 : 2; // 计算并显示发货日期 const shipDate = calculateShipDate(now, daysToAdd); document.getElementById('ship-date').textContent = formatDate(shipDate); // 启动倒计时,每秒更新一次 updateCountdown(); setInterval(updateCountdown, 1000); } // 页面加载完成后初始化 window.addEventListener('load', initShipmentInfo);
代码说明
- 日期格式化简化:使用
padStart直接补零生成两位的日/月,替代原代码的月份数组,代码更简洁 - 逻辑拆分:将日期格式化、发货日期计算、倒计时更新拆分为独立函数,可读性和维护性更强
- 倒计时逻辑:自动判断当前时间是否过了当日10:30,若已超时则自动切换到次日截止时间的倒计时
- 实时更新:通过
setInterval每秒刷新倒计时,确保时间显示准确
内容的提问来源于stack exchange,提问作者Mateusz
相关产品推荐
相关产品推荐

