3

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..')
  }
jted95
  • 1,084
  • 1
  • 9
  • 23
user15322469
  • 841
  • 1
  • 8
  • 31
  • 1
    Does this answer your question? [How to calculate date difference in JavaScript?](https://stackoverflow.com/questions/7763327/how-to-calculate-date-difference-in-javascript) – Justinas Oct 27 '22 at 06:31
  • 1
    `getDate` returns day of month, so `curTime.getDate() >= pwDate.getDate() - 90` makes no sense – Justinas Oct 27 '22 at 06:33
  • also [dayjs().subtract(90, 'days')](https://day.js.org/docs/en/manipulate/subtract) – Matt Oct 27 '22 at 06:44

2 Answers2

2

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)

ChanHyeok-Im
  • 541
  • 3
  • 11
2

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)
Mustafa Zahedi
  • 103
  • 1
  • 1
  • 9