Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate date difference in javascript

I write the code below:

var _MS_PER_Day=24*60*60*1000;
var utc1 = Date.UTC(1900, 1, 1);
var utc2 = Date.UTC(2014,11,16);
var x = Math.ceil((utc2 - utc1) / _MS_PER_Day);
alert(x);

I want to calculate the date difference between the two dates.The actual date difference is 41957 but after running my code i get 41956 ,one date less.What is wrong with my code ?

like image 903
BenjaBoy Avatar asked May 18 '26 04:05

BenjaBoy


2 Answers

Your code is calculating the difference between Feb 1, 1900 and Dec 16, 2014 (41956 days). The value month should be between 0...11 (where 0 is January). Correct the month numbers to get the expected result:

var _MS_PER_Day = 1000 * 60 * 60 * 24;
var utc1 = Date.UTC(1900, 0, 1); // Jan 01, 1900
var utc2 = Date.UTC(2014, 10, 16); // Nov 16, 2014
var x = Math.ceil((utc2 - utc1) / _MS_PER_Day);
alert(x); // 41957
like image 189
Salman A Avatar answered May 20 '26 18:05

Salman A


This is an alternate code for the above which will give you 41957.

var date1 = new Date("1/1/1900");
var date2 = new Date("11/16/2014");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
alert(diffDays);

Reference : Get difference between 2 dates in javascript?

like image 38
Progeeker Avatar answered May 20 '26 18:05

Progeeker