3

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 ?

BenjaBoy
  • 454
  • 3
  • 16
  • By my calculations the difference is 41958. – nnnnnn Nov 16 '14 at 12:13
  • @nnnn http://www.convertunits.com/dates/from/Jan+1,+1900/to/Nov+16,+20 i check in more than 5 websites it is just 41957 day, i think urs also 1 day more. – BenjaBoy Nov 16 '14 at 12:16
  • Interesting: when I said "my calculations" I had just used Excel (2010), which seems to believe erroneously that 1900 was a leap year. So yes, 41957 is correct. – nnnnnn Nov 16 '14 at 12:21

4 Answers4

4

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
Salman A
  • 262,204
  • 82
  • 430
  • 521
2

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?

Community
  • 1
  • 1
Progeeker
  • 124
  • 5
1

The months are from 0 to 11 considering 0 as January. You may also use getTime method to get the UTC timestamp in miliseconds.

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

Pankaj Goyal
  • 1,448
  • 3
  • 15
  • 25
0

I think you can use http://momentjs.com/ it give you the best 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)
flozwo
  • 1