How to find the difference between two dates in Javascript

To compute the difference between two dates in Javascript, we will first use moment js :

var date1 = moment(‘1/13/2020’);

var date2 = moment(’12/13/2020′);

console.log(date2.diff(date1, ‘days’), ‘Difference in days ‘);

The method diff allows you to find the difference in any unit and the syntax is

moment.diff(moment, ‘interval’);

Read: How to delete values ​​from an array in Javascript

To calculate the date difference in Javascript, in hours, we use:

var date1 = moment(‘1/13/2020’);

var date2 = moment(’12/13/2020′);

console.log(date2.diff(date1, ‘hours’), ‘Difference in hours’);

Using standard functions, we can subtract dates in javascript as follows:

const date1 = new Date(‘1/13/2020’);

const date2 = new Date(’12/13/2020′);

const diff_Time = Math.abs(date2 – date1);

const diff_Days = Math.ceil(diff_Time / (1000 * 60 * 60 * 24));

console.log(diff_Time + ” milliseconds”);

console.log(diff_Days + ” days”);

Read: How to convert a JSON object to String in Javascript


If you like the content, we would appreciate your support by buying us a coffee. Thank you so much for your visit and support.

 

Marianne elanotta

Marianne is a graduate in communication technologies and enjoys sharing the latest technological advances across various fields. Her programming skills include Java OO and Javascript, and she prefers working on open-source operating systems. In her free time, she enjoys playing chess and computer games with her two children.

Leave a Reply