My Experiments with Date Diff in JavaScript

Calculating the difference between two dates in JavaScript is relatively easy. First of all JavaScript provides a facility to create a Date object with various overloaded constructors. This provides a uniform way for the comparison. It also provides an ability to use the less than or greater than operator on the JavaScript Date object to check whether a particular date is before or after the other date.

Having said that, the Date does not provide any direct way to find out exact difference between the two dates in terms of days, hours, minutes and so on. However using some of the existing functions of the Date class, the date difference in the required format can be derived. Here is the complete html code along with the required JavaScript to demonstrate the same.

<title> Date Diff in JavaScript </title>
    body {
        font-family: arial;
        font-size: 18px;
	font-weight: bold;
        margin: 30px 0 0 30px;

    span {
        color: #444;
	font-weight: normal;
    .diff {
        margin-top: 20px;
<script language="JavaScript">
    function init() {
        var currentDate = new Date();
        var date1Ele = document.getElementById("date1");
        date1Ele.innerHTML = currentDate;

        var newDate = new Date(2012, 4, 21, 0, 0, 0, 0);
        var date2Ele = document.getElementById("date2");
        date2Ele.innerHTML = newDate;

        var dateDiffEle = document.getElementById("dateDiff");
        dateDiffEle.innerHTML = getDatesDifference(currentDate, newDate);

    function getDatesDifference(dateFrom, dateTo) {
        var fromMillis = dateFrom.getTime();
        var toMillis = dateTo.getTime();
        var deltaMillis = 0;
        if(fromMillis < toMillis) {
            deltaMillis = toMillis - fromMillis;
        else {
            deltaMillis = fromMillis - toMillis;
        return getFormattedDelta(deltaMillis);

    function getFormattedDelta(deltaMillis) {
        var millis = Math.floor(deltaMillis % 1000);
        var seconds = Math.floor((deltaMillis / 1000) % 60);
        var minutes = Math.floor(deltaMillis /(1000 * 60)) % 60;
        var hours = Math.floor(deltaMillis /(1000 * 60 * 60)) % 24;
        var days = Math.floor(deltaMillis /(1000 * 60 * 60 * 24));
        return days + " Day(s) " + hours + " Hour(s) " + minutes + " Minute(s) " + 
               seconds + " Second(s) and " + millis + " Millisecond(s).";

<body onLoad="init();">
    <h1>Date Diff in JavaScript</h1>
    <div>Date 1 : <span id="date1"></span></div>
    <div>Date 2 : <span id="date2"></span></div>
    <div class="diff">Date Diff : <span id="dateDiff"></span></div>

In the above code we have taken advantage of the function date.getTime() which returns the number of milliseconds since 1970/01/01. This forms a common baseline to compare 2 dates. Here is quick summary of the code.

  • Style and Body block is added just as a need to render the results to demonstrate the date difference in the required format.
  • There are three functions in the Script block which is of our interest in this example.
    • init() : This function is called on load to populate/render the values of dates and their diff.
    • getDatesDifference(dateFrom, dateTo) : This function accepts 2 date objects as an input parameter. Retrieves the milliseconds of both the dates to get the difference. This difference of milliseconds is passed to the next function for formatting.
    • getFormattedDelta(deltaMillis) : This function accepts delta milliseconds as an input and formats it in the required string. Days, Hours, Minutes, Seconds and Milliseconds are calculated from the delta milliseconds using simple arithmetic.

You may want to paste the above code as an html file and see the results in the browser. Try updating the inputs of variable newDate to see the variations. Here is a screen shot of browser after loading HTML with the above code.

Date Diff in JavaScript

Output of above code as seen on the browser

This is just an example, and one can think of returning the diff string in some other reusable format from the function getFormattedDelta(). Perhaps it could be delimited string or XML or JSON.

Complete reference of JavaScript Date object can be found here.


Posted on August 5, 2012, in JavaScript, tech, web development and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: