You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用moment.js判断用户本地时间是否处于CT时区门店营业时间范围内

门店跨时区营业状态判断方案

核心逻辑

判断门店是否营业的唯一参考是CT时区(美国中部时区,对应IANA时区标识America/Chicago)的当前实时时间,与用户所在时区完全无关,不需要做用户本地时间和CT时间的换算,自然也不存在跨时区日期匹配的问题。

实现步骤

  • 直接将当前标准时间转换为CT时区的时间对象
  • 提取CT时间对应的星期数、当前时分的总分钟数
  • 匹配预定义的营业时间规则,判断是否在营业区间内

可运行代码(基于moment-timezone)

// 营业时间规则:数组索引对应周几(0=周日,1=周一...6=周六),值为[开门总分钟数, 关门总分钟数]
const businessHours = [
  [8 * 60, 19 * 60], // 周日 8:00-19:00
  [8 * 60, 20 * 60], // 周一 8:00-20:00
  [8 * 60, 20 * 60], // 周二
  [8 * 60, 20 * 60], // 周三
  [8 * 60, 20 * 60], // 周四
  [8 * 60, 20 * 60], // 周五
  [8 * 60, 19 * 60]  // 周六 8:00-19:00
]

// 直接获取当前CT时区的时间对象
const nowCT = moment.tz('America/Chicago')
// 提取当前周几
const dayOfWeek = nowCT.day()
// 计算当前时间的总分钟数,避免小时分钟分开判断的冗余
const currentTotalMinutes = nowCT.hours() * 60 + nowCT.minutes()
// 读取对应日期的营业时间区间
const [openTime, closeTime] = businessHours[dayOfWeek]

// 最终营业状态判断
const isBusinessOpen = currentTotalMinutes >= openTime && currentTotalMinutes < closeTime

console.log(`门店当前状态:${isBusinessOpen ? '营业中' : '已歇业'}`)

原生JS实现(无需第三方库)

如果不想引入moment相关依赖,可以用浏览器原生的Intl.DateTimeFormatAPI实现:

const businessHours = [
  [8 * 60, 19 * 60],
  [8 * 60, 20 * 60],
  [8 * 60, 20 * 60],
  [8 * 60, 20 * 60],
  [8 * 60, 20 * 60],
  [8 * 60, 20 * 60],
  [8 * 60, 19 * 60]
]

// 配置CT时区时间格式化器
const ctTimeFormatter = new Intl.DateTimeFormat('en-US', {
  timeZone: 'America/Chicago',
  hour: '2-digit',
  minute: '2-digit',
  weekday: 'short',
  hour12: false
})
const timeParts = ctTimeFormatter.formatToParts(new Date())
// 映射周几数值
const weekDayMap = { Sun:0, Mon:1, Tue:2, Wed:3, Thu:4, Fri:5, Sat:6 }
const dayOfWeek = weekDayMap[timeParts.find(item => item.type === 'weekday').value]
const hours = parseInt(timeParts.find(item => item.type === 'hour').value)
const minutes = parseInt(timeParts.find(item => item.type === 'minute').value)
const currentTotalMinutes = hours * 60 + minutes
const [openTime, closeTime] = businessHours[dayOfWeek]
const isBusinessOpen = currentTotalMinutes >= openTime && currentTotalMinutes < closeTime

内容的提问来源于stack exchange,提问作者blkhwks19

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 06:54:03