如何在网页中按时区、日期及时间动态展示门店营业/歇业状态
营业状态展示时区适配修改方案
核心问题说明
原代码使用getDay()、getHours()等方法获取的是用户设备本地时区的时间,不同地区的用户访问会得到和店铺所在地不一致的营业状态。我们可以通过原生JS的Intl.DateTimeFormat接口直接获取指定时区的时间数据,无需引入第三方库。
修改后的完整代码
<span id="hoursofoperation"></span>
const operationEl = document.getElementById("hoursofoperation"); // 在这里配置店铺所在时区,使用IANA时区标识,比如北京时间为Asia/Shanghai const targetTimezone = "Asia/Shanghai"; // 从指定时区获取当前的周几、小时、分钟 const formatter = new Intl.DateTimeFormat('en-US', { timeZone: targetTimezone, weekday: 'numeric', // 周日返回0,周一到周六返回1-6,和营业时间表下标对应 hour: '2-digit', minute: '2-digit', hour12: false }); const parts = formatter.formatToParts(new Date()); const timezoneDay = parseInt(parts.find(p => p.type === 'weekday').value); const timezoneHour = parseInt(parts.find(p => p.type === 'hour').value); const timezoneMinute = parseInt(parts.find(p => p.type === 'minute').value); // 统一转为 小时*100 + 分钟 格式的整数做比较,避免小数计算误差 const nowTime = timezoneHour * 100 + timezoneMinute; // 营业时间表格式:[周几名称, 上午开门时间, 上午关门时间, 下午开门时间, 下午关门时间] // 时间统一使用 小时*100+分钟 的格式,比如8:30写为830,12:00写为1200 const weekdays = [ ["周日", 930, 1200, 1530, 2200], ["周一", 830, 1200, 1530, 1900], ["周二", 830, 1200, 1530, 1900], ["周三", 830, 1200, 1530, 1900], ["周四", 830, 1200, 1530, 1900], ["周五", 830, 1130], ["周六"] // 周六全天休息 ]; const todayRule = weekdays[timezoneDay]; let statusText = "我们已歇业"; // 先判断当天是否有营业安排,再判断是否在营业时段内 if (todayRule.length >= 3) { const [_, morningOpen, morningClose, afternoonOpen, afternoonClose] = todayRule; const inMorning = nowTime >= morningOpen && nowTime < morningClose; const inAfternoon = afternoonOpen && nowTime >= afternoonOpen && nowTime < afternoonClose; if (inMorning || inAfternoon) { statusText = "我们营业中"; } } operationEl.innerText = statusText;
关键改动说明
- 新增时区配置项,仅需修改
targetTimezone为店铺所在地对应的IANA时区标识即可适配 - 修复了原代码的时间比较bug:原代码直接拼接小数点的方式会把9点05分识别为9.5,比9.30(9.3)大导致判断错误,统一转为整数比较逻辑更严谨
- 增加了空规则判断,避免休息日无营业安排的场景出现索引报错
内容的提问来源于stack exchange,提问作者jQuery-Student1989
相关产品推荐
相关产品推荐

