w3resource

JavaScript: Difference between two dates in days

JavaScript Datetime: Exercise-8 with Solution

Write a JavaScript function to get difference between two dates in days.

Test Data:
console.log(date_diff_indays('04/02/2014', '11/04/2014'));
console.log(date_diff_indays('12/02/2014', '11/04/2014'));
Output :
216
-28

Sample Solution:-

HTML Code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript difference between two dates in days</title>
</head>
<body>
</body>
</html>

JavaScript Code:

var date_diff_indays = function(date1, date2) {
dt1 = new Date(date1);
dt2 = new Date(date2);
return Math.floor((Date.UTC(dt2.getFullYear(), dt2.getMonth(), dt2.getDate()) - Date.UTC(dt1.getFullYear(), dt1.getMonth(), dt1.getDate()) ) /(1000 * 60 * 60 * 24));
}
console.log(date_diff_indays('04/02/2014', '11/04/2014'));
console.log(date_diff_indays('12/02/2014', '11/04/2014'));

Sample Output:

216
-28

Flowchart:

Flowchart: JavaScript- Difference between two dates in days

Live Demo:

See the Pen JavaScript - Difference between two dates in days-date-ex- 8 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to test whether a date is a weekend.
Next: Write a JavaScript function to get the last day of a month.

What is the difficulty level of this exercise?



JavaScript: Tips of the Day

Converts the given array elements into <li> tags and appends them to the list of the given id.

Example:

const tips_arrayToHtmlList = (arr, listID) =>(el => ((el = document.querySelector('#' + listID)),(el += arr.map(item => '<li>${item}</li>').join(''))))();
console.log(tips_arrayToHtmlList(['item 1', 'item 2'], 'myListID'));

Output:

"null
  • ${item}
  • ${item}
  • "