Home > database >  How can I execute a condition using new Date in Javascript?
How can I execute a condition using new Date in Javascript?

Time:10-27

I have a curTime variable that is the current time using new Date() and a pwChangeDate value called from the backend data.

  let curTime = new Date();       // Thu Oct 27 2022 15:02:34 GMT 0900
  const pwDate = new Date(pwChangeDate)    // Thu Oct 20 2022 13:51:57 GMT 0900

At this time, when pwDate passes 90 days based on curTime, I want to display an alert saying "90 days have passed." and when 83 days have passed, "7 days left out of 90 days." I want to display an alert.

but if i use my code it doesn't work how can i fix it?

  const pwChangeDate = cookie.get('pwChangeDate');
  const pwDate = new Date(pwChangeDate)

  if (curTime.getDate() >=  pwDate.getDate() - 90) {
    alert('90 days have passed.')
  }

  if (curTime.getDate() >=  pwDate.getDate() - 7) {
    alert('7 days left out of 90 days..')
  }

CodePudding user response:

you can get the diff between current data and pwDate in days like this:

const pwDate = new Date('Thu Oct 20 2022 13:51:57 GMT 0900');
const diff = Math.floor((new Date - pwDate)/1000/60/60/24);

console.log(diff)

CodePudding user response:

If you want to calcuate the days difference between pwDate and curTime, you can calculate like this.

Math.floor((pwDate.getTime() - curTime.getTime()) / (1000 * 60 * 60 * 24));

getTime() method returns a time value as milliseconds.

1000 * 60 * 60 * 24 is milliseconds per day.

OR

Using some library. (date-and-time)

  • Related