Calculate date difference in javascript

I am writing 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 two dates. The actual date difference is 41957, but after running my code, I get 41956, one date less. What's wrong with my code?

+3


source to share


4 answers


This is the 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);

      



Ref: Get the difference between two dates in javascript?

+2


source


Your code calculates the difference between Feb 1, 1900 and Dec 16, 2014 ( 41956 days ). The month value must 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

      

+4


source


The months range from 0 to 11 with 0 in January. You can also use the getTime method to get the UTC timestamp in milliseconds.

var _MS_PER_Day = 1000 * 60 * 60 * 24;
var t1 = new Date(1900, 0, 1); // Jan 01, 1900
var t2 = new Date(2014, 10, 16); // Nov 16, 2014
var tdiff = Math.ceil((t2.getTime() - t1.getTime()) / _MS_PER_Day); // tdiff = 41957

      

http://www.w3schools.com/jsref/jsref_gettime.asp

+1


source


I think you can use http://momentjs.com/ this gives you a better result.

const a = new Date(YOUR_START_TIME),
      b = new Date()

let diff = moment([b.getFullYear(), b.getMonth(), b.getDate()])
  .diff(moment([a.getFullYear(), a.getMonth(), a.getDate()]), 'years', true)

      

0


source







All Articles