Search code examples
node.jsdayjs

dayjs isSameOrAfter method not working as expected


console.log(dayjs('2023-06-11T23:40:00.000Z').isSameOrAfter(dayjs('2023-06-12T13:40:00.000Z'), 'day'))

Based on my understanding of the isSameOrAfter method, it should return false when comparing the given dates since '2023-06-11T23:40:00.000Z' is not the same day nor after '2023-06-12T13:40:00.000Z'.

I would appreciate any insights into why this behavior is occurring and how I can resolve it


Solution

  • dayjs() parses dates in local time, so if your local timezone is ahead of UTC the date will be 2023-06-12..., if you want to parse it in UTC use dayjs().utc() instead.

    console.log(dayjs('2023-06-11T23:40:00.000Z').format());
    
    console.log(
      dayjs('2023-06-11T23:40:00.000Z').isSameOrAfter('2023-06-12T13:40:00.000Z', 'day')
    )
    
    console.log(
      dayjs.utc('2023-06-11T23:40:00.000Z').isSameOrAfter('2023-06-12T13:40:00.000Z', 'day')
    )
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.8/dayjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.8/plugin/utc.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.8/plugin/isSameOrAfter.js"></script>
    <script>
      dayjs.extend(window.dayjs_plugin_utc);
      dayjs.extend(window.dayjs_plugin_isSameOrAfter);
    </script>