I am trying to find the number of nights between two dates, couldn't find anywhere. Please help me with the shortest code snippet which will give the number of nights between two dates. For example, if two dates are - 18/10/2016 and 21/10/2016(Please consider the default time format i.e $scope.date = new date()) then the number of nights will be - 3
Asked
Active
Viewed 4,160 times
3
-
Possible duplicate of [How do I get the number of days between two dates in JavaScript?](https://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript) – Klesun Sep 11 '19 at 18:58
1 Answers
7
Date is formatted as mm/dd/yyy
var date1 = new Date("10/18/2016");
var date2 = new Date("10/21/2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var numberOfNights = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(numberOfNights + " nights");
It also works with daylight saving days (31th march)
var date1 = new Date("03/29/2016");
var date2 = new Date("04/01/2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var numberOfNights = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(numberOfNights + " nights");
Note
If you are handling dates many times inside your code you may check momentJS

Weedoze
- 13,683
- 1
- 33
- 63
-
-
I think this may not work as expected depending on your OS timezone, since if there is a daylight saving shift in time, some dates may have 25 or 23 effective hours in them. Possibly telling `Date` constructor that the passed date string is UTC somehow could do the trick... – Klesun Sep 11 '19 at 18:54
-