// 令时判断
javascript
// 美国夏令时判断(替换原有美冬令时判断)
export const isMeidonglingTime = (date) => !isSummerTime(date)
// 夏令时判断,非夏令时同时满足
export function isSummerTime(date = new Date()) {
const year = date.getUTCFullYear()
// 计算三月第二个周日2:00 AM ET(转换为UTC时间)
let marchStart = new Date(Date.UTC(year, 2, 1))
// 找到第一个周日
while (marchStart.getUTCDay() !== 0) {
marchStart.setUTCDate(marchStart.getUTCDate() + 1)
}
// 加7天得到第二个周日
marchStart.setUTCDate(marchStart.getUTCDate() + 7)
// 设置美东时间2:00 AM(考虑时区转换:ET在3月可能是UTC-5或UTC-4)
marchStart.setUTCHours(7) // 2:00 AM ET = 7:00 UTC(夏令时开始前ET是UTC-5)
// 计算十一月第一个周日2:00 AM ET(转换为UTC时间)
let novemberEnd = new Date(Date.UTC(year, 10, 1))
while (novemberEnd.getUTCDay() !== 0) {
novemberEnd.setUTCDate(novemberEnd.getUTCDate() + 1)
}
// 设置美东时间2:00 AM(标准时间ET是UTC-5)
novemberEnd.setUTCHours(7) // 2:00 AM ET = 7:00 UTC(夏令时结束后ET是UTC-5)
// 转换为UTC时间进行比较
const utcDate = date.getTime()
return utcDate >= marchStart.getTime() && utcDate < novemberEnd.getTime()
}
javascript
export const is16to04Time = () => {
const now = new Date()
const hours = String(now.getHours()).padStart(2, '0')
const minutes = String(now.getMinutes()).padStart(2, '0')
console.log('is16to04Time:', hours + minutes, (hours + minutes) * 1)
if ((hours + minutes) * 1 >= 1600 && (hours + minutes) * 1 <= 2359) {
return true
} else if ((hours + minutes) * 1 >= 0 && (hours + minutes) * 1 <= 400) {
return true
} else {
return false
}
}
注意里面的数字:
>=1600,指代16:00;<=2359,指代23:59;
>= 0 等于:>=00:00;<=400等于:<=04:00
javascript
export const is17to05Time = () => {
const now = new Date()
const hours = String(now.getHours()).padStart(2, '0')
const minutes = String(now.getMinutes()).padStart(2, '0')
console.log('is17to05Time:', hours + minutes, (hours + minutes) * 1)
if ((hours + minutes) * 1 >= 1700 && (hours + minutes) * 1 <= 2359) {
return true
} else if ((hours + minutes) * 1 >= 0 && (hours + minutes) * 1 <= 500) {
return true
} else {
return false
}
}
注意里面的数字:
>=1700,指代17:00;<=2359,指代23:59;
>= 0 等于:>=00:00;<=500等于:<=05:00
附上本人调用场景:(可根据自己的业务场景调用)
javascript
let timer = null
timer = setInterval(() => {
// 判断交易状态
if (isMeidonglingTime() && is17to05Time()) {
// 17:00-05:00 交易中
} else if (!isMeidonglingTime() && is16to04Time()) {
// 16:00-04:00 交易中
} else {
// 其他时间 非交易时间
}
}, 1000)
记得在组件卸载时关闭定时器:
onBeforeUnmount(()=> {clearInterval(timer)})
需要的朋友自取,如果有用的话帮忙点个关注哈!