All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

How To Compare Two Dates In JavaScript

Last Updated : Mar 11, 2024

How To Compare Two Dates In JavaScript

In this article we will show you the solution of how to compare two dates in JavaScript, in JavaScript, comparing dates typically entails determining if one date is sooner, later, or equal to another.

To do this, JavaScript offers a number of strategies and approaches. We must first make sure we have proper Date objects before we can compare two dates.

These can be produced either by parsing date strings or using the Date() constructor.

When we have our date objects, then can compare them using comparison operators such, as <, >, <=, as well as >=. It's crucial to keep in mind that whenever comparing Date objects with these operators, their actual timestamp values—and not their date representations—are used.

We must therefore exercise caution when contrasting dates with various temporal components. We can normalise the time components of both dates prior to comparison using the setHours(), setMinutes(), & setSeconds() methods to address time component concerns.

Now move to the concept of how to compare two dates in javascript.

Step By Step Guide On How To Compare Two Dates In JavaScript :-

<!DOCTYPE html>
<html>
<head>
  <title>Date Comparison</title>
</head>
<body>
  <h1>Date Comparison</h1>
  <label for="date1">Enter Date 1:</label>
  <input type="datetime-local" id="date1" required>
  <br>
  <label for="date2">Enter Date 2:</label>
  <input type="datetime-local" id="date2" required>
  <br>
  <button onclick="compareAndDisplayResult()">Compare Dates</button>
  <p id="result"></p>
  <script>
    function compareDates(date1, date2) {
      const parsedDate1 = new Date(date1);
      const parsedDate2 = new Date(date2);
      if (parsedDate1.getFullYear() < parsedDate2.getFullYear()) {
        return -1;
      } else if (parsedDate1.getFullYear() > parsedDate2.getFullYear()) {
        return 1;
      } else if (parsedDate1.getMonth() < parsedDate2.getMonth()) {
        return -1;
      } else if (parsedDate1.getMonth() > parsedDate2.getMonth()) {
        return 1;
      } else if (parsedDate1.getDate() < parsedDate2.getDate()) {
        return -1;
      } else if (parsedDate1.getDate() > parsedDate2.getDate()) {
        return 1;
      }
      if (parsedDate1.getHours() < parsedDate2.getHours()) {
        return -1;
      } else if (parsedDate1.getHours() > parsedDate2.getHours()) {
        return 1;
      } else if (parsedDate1.getMinutes() < parsedDate2.getMinutes()) {
        return -1;
      } else if (parsedDate1.getMinutes() > parsedDate2.getMinutes()) {
        return 1;
      } else if (parsedDate1.getSeconds() < parsedDate2.getSeconds()) {
        return -1;
      } else if (parsedDate1.getSeconds() > parsedDate2.getSeconds()) {
        return 1;
      } else {
        return 0;
      }
    }
    function compareAndDisplayResult() {
      const date1 = document.getElementById("date1").value;
      const date2 = document.getElementById("date2").value;
      const comparisonResult = compareDates(date1, date2);
      const resultElement = document.getElementById("result");
      if (comparisonResult === -1) {
        resultElement.textContent = "Date 1 is earlier than Date 2.";
      } else if (comparisonResult === 1) {
        resultElement.textContent = "Date 1 is later than Date 2.";
      } else {
        resultElement.textContent = "Both dates are equal.";
      }
    }
  </script>
</body>
</html>
  1. We start our code by <!DOCTYPE HTML> which includes head and body section of our code
  2. Then we use the title tag in the <head> section.
  3. The header "Date Comparison" inside the "body" section displays "Date Comparison" as the page's primary title.
  4. There are then two input fields with labels.
  5. The first input field requests that the user "Enter Date 1," whereas the second input field requests that the user "Enter Date 2."
  6. These are shown as <label> elements that are connected to the corresponding <input> elements via the for attribute & matching id values.
  7. The two input fields have the datetime-local data type, which enables users to enter a date & a time using the browser's graphical user interface.
  8. Users can click the "Compare Dates" button element that is located below the input fields to start comparing the entered dates.
  9. The compareAndDisplayResult() method should be referred to as each time the button is clicked, in step with the button detail's onclick attribute.
  10. After that, the javascript is placed inside a <script> tag.
  11. The first method, compareDates(date1, date­2), creates Date obje­cts from two date strings (date1 and date2) using the­ new Date() constructor. These­ Date objects are the­n compared to each other.
  12. In the comparison proce­ss, the year, month, and day components of the­ two dates are analyzed through various Date­ methods. These include­ getDate(), getMonth(), and ge­tFullYear().
  13. If date1 is earlier, the procedure will return -1. Conversely, if date1 is later, it will return 1. In case the dates differ by year, month, or day but are­ otherwise identical, the­ procedure will return 0.
  14. If the dates have the same ye­ars, months, and days, additional Date methods like getHours(), getMinutes(), and getSeconds() are utilized by the function to compare the time components, name­ly hours, minutes, and seconds.
  15. The compareAndDisplayResult() method is called when the "Compare Dates" button is clicked. The values submitted in the input fields are given to the compareDates() function, which compares them.
  16. Depending on the conclusion of the comparison, the function updates the text of a paragraph element (p id="result">/p>) with the id "result" to display the comparison result as a message on the website.
  17. Depending on the comparison outcome, one of these messages will pop up: A statement such as "Date 1 is earlier than Date 2," "Date 1 is later than Date 2," or "Both dates are equal."
  18. Without requiring a page refresh, the comparison result is displayed dynamically below the button when a user clicks the "Compare Dates" button & enters two dates.

Conclusion :-

As a result, we have successfully mastered the JavaScript idea of date comparison.

We also discovered how to extract and compare the year, month, day, hour, minute, & second components of dates in JavaScript using the methods of the Date object.

Date objects can be created from date strings to enable precise comparisons.

I hope this article on how to compare two dates in JavaScript helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Dikshita

Passionate Electronics and Communication Engineering student with expertise in web development (HTML, CSS, JS,PHP, Bootstrap, React.js) and content writing. Eager problem solver and tech enthusiast, adept at creating engaging web experiences.

Follow Dikshita On Linkedin 🡪