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?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

JavaScript: Tips of the Day

Add padding to the beginning of a string

const name = 'Minta Lofton';
console.log(name.padStart(13));
console.log(name.padStart(2));

With the padStart method, we can add padding to the beginning of a string. The value passed to this method is the total length of the string together with the padding. The string "Minta Lofton" has a length of 12. name.padStart(13) inserts 1 space at the start of the string, because 12 + 1 is 13.
If the argument passed to the padStart method is smaller than the length of the array, no padding will be added.

Ref: https://bit.ly/3jFRBje