Calculate the Number of Days between Two Dates using JavaScript

On MM/DD/YYYY, if you need to manipulate dates in JavaScript, you have several options. Solution 1 involves using the Date() object. Solution 2 requires obtaining date objects rather than string values from inputs to perform date subtraction. If you retrieve a value from HTML, it will be a string, so you’ll need to convert it to a date. One solution for this is to use a library. Another approach is to use the “ugly” JavaScript way. Finally, Solution 3 suggests changing the order of the month and date, with the month appearing first.


Solution 1:

var date1 = new Date("11/04/2016");
var date2 = new Date("11/19/2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
alert(diffDays);

change the format of date.

The correct format is: Month/Day/Year, written as MM/DD/YYYY.

Hope this helps.


Solution 2:


The simplest method involves utilizing the

moment.js

library.

var date1 = moment('04.11.2016', 'MM.DD.YYYY'),
    date2 = moment('19.11.2016', 'MM.DD.YYYY'),
    diffDays = date2.diff(date1, 'days'); // you can wrap it in Math.abs()

The ugly js way:

var input1 = '04.11.2016',
    parts1 = input1.split('.'),
    date1 = new Date(parts1[2], parts1[1], parts1[0]),
    input2 = '19.11.2016',
    parts2 = input2.split('.'),
    date2 = new Date(parts2[2], parts2[1], parts2[0]),
    timeDiff = Math.abs(date2.getTime() - date1.getTime()),
    diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));


Solution 3:


The order of the month and date should be changed so that the month comes first and then the date. The format should be as follows: Month, Day, Year (MM/DD/YYYY).

var date1 = new Date("11.04.2016");
var date2 = new Date("11.19.2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
alert(diffDays);

Frequently Asked Questions