JavaScript: Compare Two String Dates for Beginners

In this tutorial, we will use an function to compare two string dates in javascript.

JavaScript: Compare Two String Dates for Beginners

Here is the data comparison function:

function compareDates(d1, d2){
    const date1 = new Date(d1);
    const date2 = new Date(d2);

    if(date1.getTime() > date2.getTime()){
        console.log('${d1} is greater than ${d2} in terms of milliseconds')
    } else if(date1.getYear() < date2.getYear()){
        console.log('${d2} is greater than ${d1} in terms of years')
    } else if(date1.getDate() === date2.getDate()){
        console.log('Both dates are equal')
    }
}

compareDates("9/10/1997", "9/10/2000")
compareDates("11/11/2021", "11/1/2021")

d1 and d2 are string dates, for example: 9/10/1997

Run this code, you will see:

9/10/2000 is greater than 09/10/1997 in terms of years
11/11/2021 is greater than 11/1/2021 in terms of milliseconds