Moment js Difference Between Two Dates Example

In this tutorial we are going to share Moment Js difference between two dates. This example explain moment js difference between two days in days, months, months, years, hours, second or miliseconds.

Moment js gives us different types methods to callculate date difference between other format. Moment js diff() method to easy getting difference between two dates in days, hours, minutes and seconds in jquery, javascript, vuejs, react, angular etc.

Moment Js difference between two dates in days

This example explain Moment.js – two dates difference in number of days

<script type="text/javascript">

    let date1 = moment('01-01-2022', 'DD-MM-YYYY');
    let date2 = moment('05-01-2022', 'DD-MM-YYYY');
    let daysDiff = date2.diff(date1, 'days');

    console.log(daysDiff + ' days'); // output 4 days

</script>

Moment js difference between two dates in months

This example explain Moment.js – two dates difference in number of months

<script type="text/javascript">
    let startDate = moment('02-01-2022', 'DD-MM-YYYY');
    let endDate = moment('02-05-2022', 'DD-MM-YYYY');

    let dayDiff = endDate.diff(startDate, 'months');
    console.log('Months:' + dayDiff); // output Months:4

</script>

Moment js difference between two dates in years

This example explain Moment.js – two dates difference in number of years

<script type="text/javascript">
    let startDate = moment('02-01-2021', 'DD-MM-YYYY');
    let endDate = moment('02-05-2022', 'DD-MM-YYYY');

    let yearsDiff = endDate.diff(startDate, 'years');
    console.log('years:' + yearsDiff); // years:1

</script>

Moment js difference between two dates in hours

This example explain Moment.js – two dates difference in number of hours

<script type="text/javascript">
    let startTime = moment('02-01-2022 01:01:01', 'DD-MM-YYYY hh:mm:ss');
    let endTime = moment('03-01-2022 12:52:53', 'DD-MM-YYYY hh:mm:ss');

    let hoursDiff = endTime.diff(startTime, 'hours');
    console.log('Hours:' + hoursDiff); // output Hours:35

</script>

Moment js difference between two dates in minutes

This example explain Moment.js – two dates difference in number of minutes

<script type="text/javascript">
    let startTime = moment('02-01-2022 01:01:01', 'DD-MM-YYYY hh:mm:ss');
    let endTime = moment('03-01-2022 12:52:53', 'DD-MM-YYYY hh:mm:ss');

    let minutesDiff = endTime.diff(startTime, 'minutes');
    console.log('Minutes:' + minutesDiff); // output Minutes:2151

</script>

Moment difference between two dates in seconds

This example explain Moment.js – two dates difference in number of seconds

<script type="text/javascript">
    let startTime = moment('02-01-2022 01:01:01', 'DD-MM-YYYY hh:mm:ss');
    let endTime = moment('03-01-2022 12:52:53', 'DD-MM-YYYY hh:mm:ss');

    let secondsDiff = endTime.diff(startTime, 'seconds');
    console.log('Seconds:' + secondsDiff); // output Seconds:129112

</script>

I hope its work for you.

Leave a Comment