Home > Enterprise >  How to compare javascript dates (strings) with a specific format
How to compare javascript dates (strings) with a specific format

Time:03-31

I have two dates in a specific format (strings). I need to verify if the current date is lower than the max allowed date:

var date_current = '03_25_2022';
var date_max = '03_30_2022';

The format will always be m_d_Y. Since these are technically strings, what would be the best way to compare them as dates?

I'm using this function but I'm not sure of the approach:

function compareDates(d1, d2){
    var parts = d1.split('_');
    var d1 = Number(parts[1]   parts[2]   parts[0]);
    parts = d2.split('_');
    var d2 = Number(parts[1]   parts[2]   parts[0]);
    return d1 <= d2;
}

CodePudding user response:

You can first convert these string into date object and then compare their timestamp as follow:

function strToDate(str) {
  const splits = str.split('_');
  if (splits.length !== 3) {
    throw Error("Invalid date");
  }
  return new Date(splits[2], parseInt(splits[0]) - 1, splits[1]);
}

let dateCurrent = strToDate('03_25_2022');
let dateMax = strToDate('03_30_2022');

console.log(dateMax.getTime() > dateCurrent.getTime())

  • Related