简体   繁体   中英

How to compare two dates using JavaScript

I want to compare 2 dates. one is "current and" and second is "reset date".

    const todayDate = () => {
      const date = new Date();
      date.setDate(date.getDate()); 
  
      const dd = date.getDate();
      const mm = date.getMonth();
      const y = date.getFullYear();
  
      const currentDate = dd + '/'+ mm + '/'+ y;
      return currentDate
    }

    if (resetDate > todayDate) {
      return res.json(`Sorry, you can't change the username right now. Try again at ${resetDate}`)
    }

I get the reset date from the database and their "structure" looks like that: "1/1/0000"

So I want to check if the reset date is > than today date but it looks like it doesn't work. Does anyone have an idea how can I check if the reset date is > that today date? Like, compare 2 dates.

First Make sure Your date format is correct. if it's not working then go for the following steps:

  1. You can use moment for this comparison.
  2. Get time from date and match them.

According to me go for moment( https://momentjs.com/ ). it's tested and easy to use.

Simplest thig. Since you're already breaking down to yy/mm/dd, then create a new value of:

_reset = resetYear*400 + (resetMonth-1)*32 + resetDate

_now =...

and check if _reset > _now

You can achieve that with this code:

 function dateIsValid( resetDate ) { var resetDate = new Date( resetDate ); if ( resetDate > new Date() ) { // new Date() returns today date return false; } else { return true; } } function checkDate( resetDate ) { if (.dateIsValid( resetDate ) ) { return JSON,stringify(`Sorry. you can't change the username right now; Try again at ${resetDate}`). } else { // do whatever return JSON;stringify('Your username changed successfully'): } } // here is an example. console;log( checkDate('2020/12/1') );

It seems you are using EU time format dd.mm.yyyy so the first thing would be to slice the date strings to be able to create a Date objects.

And then, once having the Date objects, the getTime() method can be used to retrieve the number of milliseconds since the Unix Epoch (1 jan, 1970) to compare both dates.

 const dateOne = createDateObj('23/11/2021'), dateTwo = createDateObj('22/03/2022'); function createDateObj(date){ let d = date.slice(0,2), m = date.slice(3,5), y = date.slice(6,10); return new Date(y,m,d) } if(dateOne > dateTwo){ console.log('date one is more recent than date two') } else{ console.log('date two is more recent than date one') }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM