Search code examples
javascriptdate

How to compare two dates time hours and minutes


The date sent from server (in request) has the following format: '05-02-2024 10:20'

How to compare this date with the current date?

Example of an (unsuccessful) attempt:

checkDate(){
  const current = new Date().getTime();
  const dateSentFromServer = '05-02-2024 10:20';
  const myDate = Date.parse(dateSentFromServer);

  if (myDate > current) {
      return false;
  } else {
      return true;
  }
}  

EDITED:

A simple example for better description:

A post can only be seen by the user on a certain date registered in the database in a specific format (05-02-2024 10:20)

To do this, it is necessary to check whether this date has already been verified by comparing it with the current date


Solution

  • If you want to see if a timestamp before or after "now", then simply parse it and compare it to Date.now(), e.g.

    let timestamp = '05-02-2024 10:20';
    
    // Parse timestamp as day-month-year hour:min
    let [d,m,y,hr,min] = timestamp.split(/\D+/);
    
    // Is 5 Feb 2024 before now?
    console.log(new Date(y, m-1, d, hr, min) < Date.now());

    You may wish to create a separate function (or use a library) to do the parse.