Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the number of nights between two dates using AngularJs?

Tags:

angularjs

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

like image 634
shreedhar bhat Avatar asked Oct 20 '25 15:10

shreedhar bhat


1 Answers

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

like image 57
Weedoze Avatar answered Oct 22 '25 10:10

Weedoze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!