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 ?
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?
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
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
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)