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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With