Skip to main content
X

Explore your training options in 10 minutes

JavaScript Date Object: How to Compare Dates

Christina Kopecky - October 05, 2020


One thing we can do when solving coding problems is use the Date Object to compare dates and times to conditionally render certain logic in our code. This article takes a look at how to use the Date Object to compare two dates to see which one is the later (or earlier) date.

The Setup

JavaScript has a built-in Date Object we can use to access methods able to assist us in doing logic based on timestamps. To set this up, instantiate a new Date by coding the following:

const date = new Date("09-20-2020"); //2020-09-20T07:00:00.000Z

If you were to input console.log(date) , the time (the substring after the T) will differ based upon where you live by default. If you would like to work with UTC time, remove the Z and add +HH:MM or -HH:MM instead.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses










By continuing you agree to our Terms of Service and Privacy Policy , and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

Knowing how to set this up is important when we work with our compare function in the next section.

Next, take a look at the methods offered to us when using the Date constructor. One such method is getTime() . We use this method to change our Date Object to a number so it can be easily compared.

This particular method converts the date to the number of milliseconds since the epoch began (the epoch began on January 1, 1970). Here’s our getTime method:

const date = new Date("09-20-2020")
   date.getTime(); //1600585200000

Because the date is instantiated as a new Date Object, we can use dot notation to access the getTime function.

I recommend checking out the documentation for all the different types of methods you can use on the Date Object for your logic. We’re ready now to tackle our prompt.

The Prompt

Given two strings and a comparison operator, return a date that is either the least or the greatest dependent on the operator given. It is guaranteed that the two passed strings can be transformed to a Date Object.

The Steps To Solve

  1. Change the two strings to new Date Objects. Don’t forget to investigate how to pass parameters into your Date constructor!
  2. Use the getTime() method to create a number of milliseconds that have passed since Jan 1, 1970.
  3. Use a conditional statement or ternary to figure out the date needed as indicated by the passed comparison operator.
  4. Convert the milliseconds into a readable date string and return it.

Try to solve it on your own before referring to the solution!

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <style>
    body {
      font-family: 'Roboto', Courier, monospace
    }
  </style>
</head>
<body>
  <h1>Date Comparison</h1>
    <label for="comparison">Comparison (Choose One)</label>
    <div id="comparison" value="more.value">
      <input name="compare" type="radio" id="less" value=""/>
          <label for="less"> &lt; </label>
      <input name="compare" type="radio" id="more" checked value=""/>
          <label for="more"> &gt;= </label>
    </div>
 <br/>
    <label for="date-1">Date 1:</label>
    <input id="date-1" value="" type="date" name="date1" />
    <label for="date-2">Date 2:</label>
    <input id="date-2" value="" type="date" name="date2" />
    <input id="submit-button" type="submit" />
    <div id="demo"></div>
    <script>
        const handleSubmit = (date1, date2, compare) => {
        //to compare : getTime of each date
        date1Arr = date1.split("-");
        date2Arr = date2.split("-");
              //year, month (month is zero-based), day
        let d1 = new Date(date1Arr[0], date1Arr[1] - 1, date1Arr[2]).getTime();
        let d2 = new Date(date2Arr[0], date2Arr[1] - 1, date2Arr[2]).getTime();
        // getTime gets the number of milliseconds since Jan 1 1970. So the higher the number, the later the date.
        //use conditional or ternary to return Comparison
        let timeDisplay;
        if(compare === ">=") {
              timeDisplay = d1 >= d2 ? d1 : d2;
        } else {
              timeDisplay = d1 < d2 ? d1 : d2;
        }
        let timetoDisplay = new Date(timeDisplay);  
        document.getElementById("demo").innerHTML = timetoDisplay.toDateString();
    }
    let date_1 = document.getElementById("date-1");
    let date_2 = document.getElementById("date-2");
    document.getElementById("submit-button").addEventListener("click", (e) => handleSubmit(date_1.value, date_2.value, more.checked ? '>=' : '<'))
    </script>
  </body>
</html>

Dates in JavaScript can be confusing at first, but with a little practice, you’ll get it in no time. Here, we’ve looked at how to set up a new date in JavaScript and access a method on its constructor. We’ve also looked at how to compare two dates to see which was the greatest or least depending on the operator that was passed in to the function.

Once you have a handle on this, I recommend taking a look at how to sort an array of items by the date they were added to the array, ascending or descending. Have fun and keep at it!

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

What's Next?

Christina Kopecky

About the author: Christina is an experienced technical writer, covering topics as diverse as Java, SQL, Python, and web development. She earned her Master of Music in flute performance from the University of Kansas and a bachelor's degree in music with minors in French and mass communication from Southeast Missouri State. Prior to joining the Career Karma team in June 2020, Christina was a teaching assistant, team lead, and section lead at Lambda School, where she led student groups, performed code and project reviews, and debugged problems for students. Christina's technical content is featured frequently in publications like Codecademy, Repl.it, and Educative.

Skip to main content