How to Calculate Hours Difference Between Two Dates in Javascript?


Share:
 | Published By: Admin | Published On: Jan 22, 2022 | Category: Javascript

Hi Dev,

Here, I will show you how to calculate hours difference between two dates in javascript?. This tutorial will give you simple example of calculate hours difference between two dates in javascript example. I would like difference between two dates calculat in hour.

I would like to share with you javascript get between two date difference hours javascript. I explained simply about between two dates javascript calculate hours.

Let's start following example.

Solution:

<script type="text/javascript">

    function timeDiffCalc(dateFuture, dateNow) {

        let diffInMilliSeconds = Math.abs(dateFuture - dateNow) / 1000;

        /// calculate hours
        const hours = Math.floor(diffInMilliSeconds / 3600) % 24;
        diffInMilliSeconds -= hours * 3600;

        let difference = '';

        difference += (hours === 0 || hours === 1) ? `${hours} hour ` : `${hours} hours `;

        return 'Calculated = ' + difference;
    }

    console.log(timeDiffCalc(new Date('2022/08/1 01:40:00'), new Date('2022/12/8 12:10:00')));
  	
</script>

Output:
Calculated = 10 hours
Share: