0

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;
}
1
  • Use split() to split it into month, day, year. Then call new Date() to create a date from it (don't forget to subtract 1 from the month). Then compare the dates. Commented Mar 30, 2022 at 16:04

1 Answer 1

1

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())

Sign up to request clarification or add additional context in comments.

4 Comments

This seems better than my current function. Is there an advantage to do this by converting it to a Date object instead of comparing the sum of the number values of the original strings? (i added my current approach to the original post btw)
@AndresSK Yes, there are certain use cases for 1_1_2021 and 12_31_2020, your function would say 12_31_2020 is bigger than 1_1_2021. Since sum for 12_31_2020 => 2063 and for 1_1_2021 => 2023.
You'd have to weight the parts of the sum for your approach to work: 40*parts[1] + parts[2] + 1000*(parts[0] - 1000) or similar. 12_31_2020 => 1,020,511 and for 1_1_2021 => 1,021,041
@Ashok Completely understood. Just applied your solution and it works. Marked it as the accepted answer, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.