calculate the number of days between two dates in JavaScript

How to Calculate the Number of Days Between Two Dates in JavaScript

If you wish to calculate the number of days between two dates using the JavaScript programming language. You have to use this math function, Math.floor() method provided by JavaScript, to calculate the number of days between the two dates. Also, you have to use the date object for any calculation to specify the date using the new Date(). 




JavaScript is a flexible programming language that can be used on both the front-end and the back-end. It is one of the core technologies of web development that allows you to execute complex features on web pages and more. JavaScript is an essential part of web functionality, all web browsers come with built-in engines that execute JavaScript. JavaScript is either included in a .js file or embedded into a web page.  


Calculating the Number of Days Between Two Dates


To calculate the number of days between two dates in JavaScript you need to use the date object. For this, begin by getting the millisecond value of the date with the help of the in-built JavaScript getTime() function. Now, when both the dates get converted, move further by subtracting the later one from the newer one. The result will return to you the difference in milliseconds. Next, to calculate the final results you need to divide the difference (calculated in milliseconds) of both the dates by the number of milliseconds in a single day. 








Step 1: Describe two dates using, new Date()


Step 2: Calculate the time difference between the two dates with the use of date2.getTime() – date1.getTime();


Step 3: Calculate the no. of days between two dates and divide the time difference of both the dates by no. of milliseconds in a day


Step 4: Print the final result using the document.write() 


The following JavaScript program will illustrate the solution:




<script type="text/javascript">

function findDiff(){

var dob1= document.getElementById("dob1").value;

var dob2= document.getElementById("dob2").value;

var date1 = new Date(dob1);

var date2=new Date(dob2); 

var ONE_DAY = 1000 * 60 * 60 * 24

var d1 = date1.getTime()

var d2 = date2.getTime()

var diff = Math.abs(d1 - d2)







Enter Date1(yyyy-mm-dd): <input type="text" name="dob1" id="dob1" />

Enter Date2(yyyy-mm-dd): <input type="text" name="dob2" id="dob2" />

Number of days: <input type="text" name="days" id="days" />

<input type="submit" value="calculate" onclick="findDiff();">







If you are trying to find out the number of days between two dates? If you want to count working days between two dates or just if you want to know the number of days between today and some date in the past or future. Whatever your interest is, the above example will surely provide a solution and you will be able to calculate the number of days between any two dates with the help of JavaScript.