1const date1 = new Date('7/13/2010');
2const date2 = new Date('12/15/2010');
3console.log(getDifferenceInDays(date1, date2));
4console.log(getDifferenceInHours(date1, date2));
5console.log(getDifferenceInMinutes(date1, date2));
6console.log(getDifferenceInSeconds(date1, date2));
7
8function getDifferenceInDays(date1, date2) {
9 const diffInMs = Math.abs(date2 - date1);
10 return diffInMs / (1000 * 60 * 60 * 24);
11}
12
13function getDifferenceInHours(date1, date2) {
14 const diffInMs = Math.abs(date2 - date1);
15 return diffInMs / (1000 * 60 * 60);
16}
17
18function getDifferenceInMinutes(date1, date2) {
19 const diffInMs = Math.abs(date2 - date1);
20 return diffInMs / (1000 * 60);
21}
22
23function getDifferenceInSeconds(date1, date2) {
24 const diffInMs = Math.abs(date2 - date1);
25 return diffInMs / 1000;
26}
1/* difference between date1 and date2 in days (date2 - date1) */
2/* date1 and date 2 are already javascript date objects */
3function dateDifference(date2, date1) {
4 const _MS_PER_DAY = 1000 * 60 * 60 * 24;
5
6 // Discard the time and time-zone information.
7 const utc1 = Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate());
8 const utc2 = Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate());
9
10 return Math.floor((utc2 - utc1) / _MS_PER_DAY);
11}
1const date1 = new Date('7/13/2010');
2const date2 = new Date('12/15/2010');
3const diffTime = Math.abs(date2 - date1);
4const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
5console.log(diffTime + " milliseconds");
6console.log(diffDays + " days");
1const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
2
3// Example
4diffDays(new Date('2014-12-19'), new Date('2020-01-01')); // 1839