skip to Main Content

I have a Date object and I want to check if it’s tomorrow.

const dateToCheck: Date //Sat Jun 01 2024 09:00:00 GMT-0700

I calculated tomorrow like this:

const tomorrow = moment().add(1, 'day')

The start and end of tomorrow are found like this:

tomorrow.startOf('day') //Sat Jun 01 2024 00:00:00 GMT-0700
tomorrow.endOf('day') //Sat Jun 01 2024 23:59:59 GMT-0700

When I try to determine if the date I’m checking is tomorrow, it’s false:

var isTomorrow = moment(dateToCheck).isBetween(
  tomorrow.startOf('day'),
  tomorrow.endOf('day'),
)
console.log(isTomorrow) //false

As far as I can tell, isTomorrow should be true because Sat Jun 01 2024 09:00:00 is between Sat Jun 01 2024 00:00:00 and Sat Jun 01 2024 23:59:59.

Any idea what I’m doing wrong?

2

Answers


  1. For more accuracy I’d convert them to ECMAScript epoch and then treat them as integers…

    var D1='Sat Jun 01 2024 23:59:59';
    
    var D2='Sat Jun 01 2024 00:00:00';
    
    
    D1=new Date(D1).getTime()/1000;
    
    D2=new Date(D2).getTime()/1000;
    
    
    if(D1-D2 < 86400){
    
     // same day
    
    } else {
    
     // next day
    
    }
    

    Or something like that.

    Login or Signup to reply.
  2. startOf and endOf modify the original Moment object. When you call isBetween(tomorrow.startOf('day'), tomorrow.endOf('day')) the isBetween function receives the same object for the start and end dates.

    You need to make copies of the tomorrow object when calling the function:

    const isTomorrow = moment(dateToCheck).isBetween(
      moment(tomorrow).startOf('day'),
      moment(tomorrow).endOf('day')
    )
    console.log(isTomorrow) // true
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search