Comparing two date in JavaScript

This is an article to show how to calculate two date difference using JavaScript.

By subtracting two date java script returns difference in milliseconds so if we want to show difference in days then we have to convert milliseconds value into days by multiplying some factor.

Milliseconds * 1000 = Seconds
Seconds * 60 = Minutes
Minutes * 60 = Hours
Hours * 24 = Days

How to Use this code:-

Just copy and paste Java Script code given bellow and pass the parameters that is id's of Startdate textbox and EndDate textbox.

function Test(tbStartDateID, tbEndDateID) {

    var startDate = document.getElementById(tbStartDateID).value;
    var endDate = document.getElementById(tbEndDateID).value;

    //Difference in milliseconds

    var timeDiff = Date.parse(endDate) - Date.parse(startDate);
    if (Date.parse(endDate) > Date.parse(startDate)) {
        //show the date diffrent in Days in two no of fraction no.

        daysDiff = Math.round(Math.abs(timeDiff / (1000 * 60 * 60 * 24)) * 10);
        alert(Math.abs(daysDiff / 10) + ' Days');

        //Show the date diffrent in Month
        alert(Math.abs(daysDiff * 30 / 10) + ' Month')
    }
    else {
        alert("StartDate must be lesser than endDate");
    }

}

Popular Posts