To check whether an input date is equal to today's date, we can compare the date parts while ignoring the time. JavaScript provides methods such as setHours() and toDateString() for this purpose.
These are the following approaches to check if an input date is today's date:
Approach 1: Using setHours() Method
In this approach, we create Date objects for the input date and today's date. We then set the hours, minutes, seconds, and milliseconds of both dates to 0 using setHours(0, 0, 0, 0). After removing the time portion, we compare the two dates.
Example: In this example, we check whether the date entered by the user is equal to today's date.
<!DOCTYPE HTML>
<html>
<head>
<title>
Check if Input Date Is Today's Date
</title>
<style>
#geeks {
color: green;
font-size: 29px;
font-weight: bold;
}
</style>
</head>
<body>
<b>
Enter a date and check if it is
the same as today's date.
</b>
<br><br>
Type date:
<input id="date" placeholder="mm/dd/yyyy">
<br><br>
<button onclick="gfg();">
Click Here
</button>
<p id="geeks"></p>
<script>
let down = document.getElementById("geeks");
function gfg() {
let date = document.getElementById("date").value;
let inpDate = new Date(date);
let currDate = new Date();
if (
inpDate.setHours(0, 0, 0, 0) ===
currDate.setHours(0, 0, 0, 0)
) {
down.innerHTML =
"The input date is today's date";
} else {
down.innerHTML =
"The input date is different from today's date";
}
}
</script>
</body>
</html>
Approach 2: Using toDateString() Method
In this approach, we use the toDateString() method to convert both the input date and today's date into strings containing only the date portion. We then compare these strings to determine whether both dates are the same.
Example: In this example, we compare the input date with today's date using toDateString().
<!DOCTYPE HTML>
<html>
<head>
<title>
Check if Input Date Is Today's Date
</title>
<style>
#geeks {
color: green;
font-size: 29px;
font-weight: bold;
}
</style>
</head>
<body>
<b>
Enter a date and check if it is
the same as today's date.
</b>
<br><br>
Type date:
<input id="date" placeholder="mm/dd/yyyy">
<br><br>
<button onclick="gfg();">
Click Here
</button>
<p id="geeks"></p>
<script>
let down = document.getElementById("geeks");
function gfg() {
let date = document.getElementById("date").value;
let inpDate = new Date(date);
let currDate = new Date();
if (
currDate.toDateString() ===
inpDate.toDateString()
) {
down.innerHTML =
"The input date is today's date";
} else {
down.innerHTML =
"The input date is different from today's date";
}
}
</script>
</body>
</html>