Home > OS >  Compare two dates and then count to zero with the diff value
Compare two dates and then count to zero with the diff value

Time:04-25

I have two dates.

1. the current date: new Date() // Today
2. the date when anything should expire new Date(2022, 3, 27)

I need the value between this two das (the difference is 2 days), but I need the date value from the difference between these dates so I can count -1 every second

Days| Hours | Minutes | second
 00    23        10        55

I use date-fns lib. How I make it ? can anyone help me ?

€:

Code:

  const dif = () => {
    if(expire_date) {
      const d = differenceInHours(expire_date, new Date());
      console.log(d);
    }
  };

  dif();

CodePudding user response:

you can try something like this

const secTimer = setInterval(() => {
        const msDiff =
          new Date(item.discount_date).getTime() - new Date().getTime();
        const daysDiff = Math.floor(msDiff / (1000 * 60 * 60 * 24));
        const hrsDiff = Math.floor(
          (msDiff - daysDiff * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
        );
        const mmDiff = Math.floor(
          (msDiff -
            daysDiff * (1000 * 60 * 60 * 24) -
            hrsDiff * (1000 * 60 * 60)) /
            (1000 * 60)
        );
        const ssDiff = Math.floor(
          (msDiff -
            daysDiff * (1000 * 60 * 60 * 24) -
            hrsDiff * (1000 * 60 * 60) -
            mmDiff * (1000 * 60)) /
            1000
        );
        setDay(daysDiff);
        setHrs(hrsDiff);
        setMm(mmDiff);
        setSs(ssDiff);
   
    }, 1000);

use usestate for day, hrs, min, secs.

CodePudding user response:

You can use monentjs

moment('2019-05-11').isSame('2019-05-11','day'); // true

moment('2019-05-11').isSame('2019-05-12','day'); // false

"Compare two dates in JavaScript using moment.js - Poopcode" https://poopcode.com/compare-two-dates-in-javascript-using-moment/amp/

I use moment both for react and nodejs

Read all about it and the different advanced functions in the api guide "Moment.js | Guides" https://momentjs.com/guides/

  • Related