如何使用Day.js判断指定日期与目标日期是否同月同日?
如何判断不同时区的日期是否为同月同日
先修正你代码里的语法问题:数组中每个对象之间必须加逗号,否则会触发语法错误,修正后的数组如下:
let dates = [ {slot: '2023-01-31T18:45:00-06:00'}, {slot: '2023-01-31T19:00:00-06:00'}, {slot: '2023-01-31T19:15:00-06:00'}, {slot: '2023-01-31T19:30:00-06:00'}, {slot: '2023-01-31T19:45:00-06:00'}, {slot: '2023-01-31T20:00:00-06:00'} ]
接下来解决核心困惑:你看到的两个日期字符串都写着1月31日,但因为时区偏移不同,它们对应的UTC时间其实分属不同日期:
Tue Jan 31 2023 00:00:00 GMT+0100转成UTC是2023-01-30T23:00:00Z2023-01-31T18:45:00-06:00转成UTC是2023-02-01T00:45:00Z
所以直接用isSame('day')会返回false,因为dayjs默认会基于实例的时区(或UTC)判断自然日。
根据你的需求,有两种可行方案:
方案1:直接比较日期的月和日
如果只需要判断两个日期字符串显示的月、日是否一致,不用考虑时区转换后的实际日期,可以直接提取月和日的值来比较:
let dates = [ {slot: '2023-01-31T18:45:00-06:00'}, {slot: '2023-01-31T19:00:00-06:00'}, {slot: '2023-01-31T19:15:00-06:00'}, {slot: '2023-01-31T19:30:00-06:00'}, {slot: '2023-01-31T19:45:00-06:00'}, {slot: '2023-01-31T20:00:00-06:00'} ] const targetDate = dayjs('Tue Jan 31 2023 00:00:00 GMT+0100'); // dayjs里月份从0开始,1月对应0 const targetMonth = targetDate.month(); const targetDay = targetDate.date(); dates.forEach(x => { const oneSlot = dayjs(x.slot); if (oneSlot.month() === targetMonth && oneSlot.date() === targetDay) { console.log("Yes"); } else { console.log("No"); } })
这种方式只看dayjs解析后得到的本地时区月日,不考虑跨时区的日期变化。
方案2:统一时区后比较自然日
如果需要判断两个时间点在同一个时区下是否属于同月同日(比如都转到UTC或GMT+01时区),需要用到dayjs的时区插件dayjs-timezone:
先安装插件:
npm install dayjs-timezone
然后修改代码:
const dayjs = require('dayjs'); const timezone = require('dayjs/plugin/timezone'); const utc = require('dayjs/plugin/utc'); // 加载插件 dayjs.extend(utc); dayjs.extend(timezone); let dates = [ {slot: '2023-01-31T18:45:00-06:00'}, {slot: '2023-01-31T19:00:00-06:00'}, {slot: '2023-01-31T19:15:00-06:00'}, {slot: '2023-01-31T19:30:00-06:00'}, {slot: '2023-01-31T19:45:00-06:00'}, {slot: '2023-01-31T20:00:00-06:00'} ] // 将目标日期转换到指定时区,比如GMT+01对应的Europe/Paris const targetDate = dayjs('Tue Jan 31 2023 00:00:00 GMT+0100').tz('Europe/Paris'); dates.forEach(x => { // 把每个slot的日期也转成同一时区 const oneSlot = dayjs(x.slot).tz('Europe/Paris'); if (oneSlot.isSame(targetDate, 'day') && oneSlot.isSame(targetDate, 'month')) { console.log("Yes"); } else { console.log("No"); } })
这种方式会把所有时间统一到同一个时区,再判断是否属于同一天和同一月,结果更符合实际时区的自然日逻辑。
内容的提问来源于stack exchange,提问作者Alexa
相关产品推荐
相关产品推荐

