How to Compare dates in JavaScript?

28-Apr-2023

.

Admin

How to Compare dates in JavaScript?

This simple article demonstrates of compare two dates with javascript. you will learn compare two dates using javascript. I’m going to show you about compare two dates using javascript. I’m going to show you about how to compare two string dates in javascript. Follow bellow tutorial step of javascript date comparison in javascript.

To compare dates in JavaScript, you can use the comparison operators such as "<", ">", "<=", ">=". You can also use the getTime() method to get the time value of each date and then compare them.

Here's an example:

Example 1:


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Compare dates in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

var date1 = new Date("2021-01-01");

var date2 = new Date("2021-02-01");

if (date1 < date2) {

console.log("date1 is before date2");

} else if (date1 > date2) {

console.log("date1 is after date2");

} else {

console.log("date1 and date2 are equal");

}

</script>

</html>

In this example, we create two Date objects representing January 1st and February 1st of 2021. We then use the "<" operator to compare them. Since January comes before February, the output will be "date1 is before date2".

You can also use the getTime() method to get the time value of each date and then compare them like this:

Example 2:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Compare dates in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

var date3 = new Date("2020-12-31");

var date4 = new Date("2020-12-30");

if (date3.getTime() > date4.getTime()) {

console.log("date3 is after date4");

} else if (date3.getTime() < date4.getTime()) {

console.log("date3 is before date4");

} else {

console.log("date3 and date4 are equal");

}

</script>

</html>

In this example, we create two Date objects representing December 31st and December 30th of 2020. We then use the getTime() method to get their time values and compare them using ">" and "<". Since December 31st comes after December 30th, the output will be "date3 is after date4".

#JavaScript