How to Perform Date Comparison With the Date Object in JavaScript
constcompareDates=(d1, d2)=>{let date1 =newDate(d1).getTime();let date2 =newDate(d2).getTime();if(date1 < date2){console.log(`${d1} is less than ${d2}`);}elseif(date1 > date2){console.log(`${d1} is greater than ${d2}`);}else{console.log(`Both dates are equal`);}};compareDates("06/21/2022","07/28/2021");compareDates("01/01/2001","01/01/2001");compareDates("11/01/2021","02/01/2022");// This will return:// "06/21/2022 is greater than 07/28/2021"// "Both dates are equal"// "11/01/2021 is less than 02/01/2022"
// We initialize the Date() object with the current date and timeconst date1 =newDate();// We initialize a past dateconst date2 =newDate('2018-04-07 12:30:00');// Let's see if the first date is equal, more recent or less recent than the second dateif(date1.getTime()=== date2.getTime()){console.log('The dates are equal');}elseif(date1.getTime()> date2.getTime()){console.log(date1.toString()+' is more recent than '+ date2.toString());}else{console.log(date1.toString()+' is less recent than '+ date2.toString());}
var x =newDate('2013-05-23');var y =newDate('2013-05-23');// less than, greater than is fine:
x < y;=>false
x > y;=>false
x === y;=>false, oops!// anything involving '=' should use the '+' prefix// it will then compare the dates' millisecond values+x <=+y;=>true+x >=+y;=>true+x ===+y;=>true
// solution is convert date to time by getTime()
start = startDate.getTime();
end = endDate.getTime();
current = date.getTime();if(start <= current && current <= end){// do something here}
var date1 =newDate();var date2 =newDate();if(date1.getTime()=== date2.getTime()){// 1605815698393 === 1605815698393 console.log("Dates are equal");}else{console.log("Dates are Not equal");}
Comparing two dates is as simple asvar differenceInMs = dateNewer - dateOlder;So, convert the timestamps back into Date instances
var d1 =newDate('2013-08-02T10:09:08Z'),// 10:09 to
d2 =newDate('2013-08-02T10:20:08Z');// 10:20 is 11 minsGet the difference
var diff = d2 - d1;Formatthisas desired
if(diff >60e3)console.log(Math.floor(diff /60e3),'minutes ago');elseconsole.log(Math.floor(diff /1e3),'seconds ago');// 11 minutes ago
let myDate =newDate("January 13, 2021 12:00:00");let yourDate =newDate("January 13, 2021 15:00:00");if(myDate < yourDate){console.log("myDate is less than yourDate");// will be printed}if(myDate > yourDate){console.log("myDate is greater than yourDate");}