• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • Home
  • Learn to Code
    • Python
    • JavaScript
  • Code Snippets
    • HTML
    • JavaScript
    • jQuery
    • PHP
    • Python
    • SAS
    • Ruby
  • About
You are here: Home / JavaScript / Using JavaScript to Compare Dates

Using JavaScript to Compare Dates

March 3, 2022 Leave a Comment

We can use JavaScript to compare dates using the getTime() method. The JavaScript getTime() method converts dates into the number of milliseconds since January 1st, 1970.

var date1 = new Date('2019-01-01');
var date2 = new Date('2020-01-01');

if (date1.getTime() < date2.getTime()) {
   console.log("date2 is after date1");
} else {
   console.log("date1 is after date1");
}

// This will output to the log "date2 is after date1"


Comparing dates in JavaScript is easy. We can use the JavaScript getTime() method to convert the dates into milliseconds, and then compare the milliseconds to each other to determine which is greater.

Then we can just use regular comparison operators like < and > to compare the dates.

The getTime() method returns the number of milliseconds since January 1, 1970. If a date is before this time, a negative number will be returned. Let’s look at some quick examples.

var date1 = new Date('2019-01-01');
var date2 = new Date('2030-01-20');
var date3 = new Date('1970-01-01');
var date4 = new Date('1970-01-02');
var date5 = new Date('1950-09-14');
var result1 = date1.getTime();
var result2 = date2.getTime();
var result3 = date3.getTime();
var result4 = date4.getTime();
var result5 = date5.getTime();

Which would result in the following:

result1 = 1546300800000;
result2 = 1895097600000;
result3 = 0;
result4 = 86400000;
result5 = -609033600000;

To see if one date is after another, we just need to compare them in an if conditional statement.


var date1 = new Date('2019-01-01');
var date2 = new Date('2030-01-20');

var result1 = date1.getTime(); // 1546300800000
var result2 = date2.getTime(); // 1895097600000

if (result1 > result2) {
   console.log("date1 is after date2");
} ekse if (result1 < result2) (
   console.log("date2 is after date1");
)

// This will log "date2 is after date1" because 1546300800000 is less than 1895097600000

An Example of Using JavaScript to Compare Two Dates

When working with a web page, sometimes we need to compare dates to some time in the future and change the content on the web page based on what time it is.

In this example, let’s create a script that compares the current time to a time set 1 minute in the future.

Then, every 10 seconds, using the JavaScript setInterval() method, we will compare the current time to the time set 1 minute in the future. At each checkpoint, we will add content to a div.

Once the current time passes the 1 minute mark, we will let the user know with new text. Here is the HTML:

<style>.red-color span { color: red; } .green-color span { color: green; }</style>
<div id="div1">
  <div>The current date and time is: <span id="currDateTime"></span></div>
  <div>We will check every 10 seconds to see if it is past <span id="newDateTime"></span>.</div>
</div>
<div id="click-me" onclick="stopScript()">Stop script</div>

The first step is to get a time 1 minute in the future, and show the user this time by adding text to the span tags using JavaScript above.

To create the time 1 minute in the future, we convert the current time into milliseconds using the getTime() method, then add 60000 milliseconds to it. Then, for display purposes, we convert it back to a date using the JavaScript new Date() method.

Next, we will set up the JavaScript code to check every 10 seconds if we have passed the 1 minute mark since page load. We can use the innerHTML() method to keep the user updated.

Every 10 seconds, the script will insert an element in the div giving the current time.

If the current time is less than the new time we created (1 minute in the future) we will highlight the text in red. Once one minute has passed, the update will highlight the text with the color green.

To display the dates in a more user-friendly format, we will use the JavaScript toLocaleString() method.

Finally, we also include an option for the user to end the updates by clicking a button that will call the clearInterval() method to kill the script.

Here is the Javascript code:

//Here we will create the current date and time, the new date and time, and fill the span divs in the html.
var currDate = new Date();
document.getElementById("currDateTime").textContent = currDate.toLocaleString('en-US', { dateStyle: 'full', timeStyle: 'long'});
var dateConversion = currDate.getTime();
var futureDateInTime = dateConversion + 60000;
var futureDate = new Date(futureDateInTime);
document.getElementById("newDateTime").textContent = (futureDate.toLocaleString('en-US', { dateStyle: 'full', timeStyle: 'long'}));
//We create a function that will run every 10 seconds
var runningInterval = setInterval(function () {
  //Create a new date and compare it to the future date we created earlier (futureDateInTime)
  var newCurrDate = new Date();
  var newCurrConversion = newCurrDate.getTime();
  var newCurrDateFormatted = newCurrDate.toLocaleString('en-US', { dateStyle: 'full', timeStyle: 'long'});
  var futureDateFormatted = futureDate.toLocaleString('en-US', { dateStyle: 'full', timeStyle: 'long'});
  //We will compare times and change text/styles based on the results
  if( newCurrConversion > futureDateInTime ){
    //The newly created time is after the set time
    document.getElementById("div1").innerHTML = document.getElementById("div1").innerHTML + ('<div class="new-update green-color">The current time is ' + newCurrDateFormatted + ' which is <span>AFTER</span> ' + futureDateFormatted + '</div>');
  } else {
    document.getElementById("div1").innerHTML = document.getElementById("div1").innerHTML + ('<div class="new-update red-color">The current time is ' + newCurrDateFormatted + ' which is </span>BEFORE</span> ' + futureDateFormatted + '</div>');
  }
}, 10000);

function stopScript(){
  clearInterval(runningInterval);
  document.getElementById("div1").innerHTML = document.getElementById("div1").innerHTML + ('<div class="new-update">Stopped. No more times will be displayed.</div>');
}

The final code and output for this example is below:

Code Output:

The current date and time is:
We will check every 10 seconds to see if it is past .

Stop script

Full Code:

<style>.red-color span { color: red;} .green-color span { color: green;}</style>
<div id="div1">
  <div>The current date and time is: <b><span id="currDateTime"></span></b></div>
  <div>We will check every 10 seconds to see if it is past <b><span id="newDateTime"></span></b>.</div>
</div>
<br>
<div id="click-me" onclick="stopScript()">Stop script</div>

<script>

var currDate = new Date();
document.getElementById("currDateTime").textContent = currDate.toLocaleString('en-US', { dateStyle: 'full', timeStyle: 'long'});
var dateConversion = currDate.getTime();
var futureDateInTime = dateConversion + 60000;
var futureDate = new Date(futureDateInTime);
document.getElementById("newDateTime").textContent = (futureDate.toLocaleString('en-US', { dateStyle: 'full', timeStyle: 'long'}));
var runningInterval = setInterval(function () {
  var newCurrDate = new Date();
  var newCurrConversion = newCurrDate.getTime();
  var newCurrDateFormatted = newCurrDate.toLocaleString('en-US', { dateStyle: 'full', timeStyle: 'long'});
  var futureDateFormatted = futureDate.toLocaleString('en-US', { dateStyle: 'full', timeStyle: 'long'});
  if( newCurrConversion > futureDateInTime ){
    document.getElementById("div1").innerHTML = document.getElementById("div1").innerHTML + ('<div class="new-update green-color">The current time is ' + newCurrDateFormatted + ' which is <span>AFTER</span> ' + futureDateFormatted + '</div>');
  } else {
    document.getElementById("div1").innerHTML = document.getElementById("div1").innerHTML + ('<div class="new-update red-color">The current time is ' + newCurrDateFormatted + ' which is <span>BEFORE</span> ' + futureDateFormatted + '</div>');
  }
}, 10000);

function stopScript(){
  clearInterval(runningInterval);
  document.getElementById("div1").innerHTML = document.getElementById("div1").innerHTML + ('<div class="new-update">Stopped. No more times will be displayed.</div>');
}

</script>

Hopefully this article has been useful in helping you understand how to use JavaScript to Compare Dates.

Other Articles You'll Also Like:

  • 1.  Using JavaScript to Stop a Timer
  • 2.  Create Array of Zeros in JavaScript
  • 3.  Using JavaScript to Replace a Space with an Underscore
  • 4.  JavaScript acos – Find Arccosine and Inverse Cosine of Number
  • 5.  How to Generate a Random Letter In JavaScript
  • 6.  How in JavaScript to Get the Day of the Week
  • 7.  Using JavaScript to Get a Random Number Between 1 and 100
  • 8.  How to Repeat Character N Times in JavaScript
  • 9.  Using JavaScript to Get a Random Number Between Range of Numbers
  • 10.  JavaScript Change Background Color of Element

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy