Open In App

How to Get Hours Difference Between Two Dates in Moment Js?

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Moment.js library has a set of powerful functions for date and time manipulation, including calculating differences between dates. To get the hours difference between two dates, you can use various methods provided by Moment.js.

Run the below command before running the code in your local system:

npm i moment

These are the following approaches we are going to discuss:

Using diff() Method with hours

In this approach, we use the diff() method from Moment.js to calculate the difference between two dates directly in hours. By specifying 'hours' as the unit, Moment.js computes the total number of hours between date1 and date2.

Syntax:

moment().diff(Moment|String|Number|Date|Array, String, Boolean);

Example: The below example uses a Method with hours to Get the hours difference between two dates in Moment Js

JavaScript
// script.js

const moment = require('moment');
const date1 = moment('2024-07-20T10:00:00');
const date2 = moment('2024-07-22T15:00:00');
const res = date2.diff(date1, 'hours');
console.log(`Hours difference: ${res}`);

Output:

Hours difference: 53

Using as() Method with duration

In this approach, moment.duration(date2 - date1) creates a duration object by subtracting date1 from date2, resulting in the time difference in milliseconds. The as('hours') method then converts this duration into hours, providing the difference between the two dates in hours.

Syntax:

 moment.duration(date2 - date1).as('hours');

Example: The below example uses as Method with duration to Get hours difference between two dates in Moment Js

JavaScript
// script.js
const moment = require('moment');
const date1 = moment('2024-07-24T08:00:00');
const date2 = moment('2024-07-24T14:30:00');

const duration = moment.duration(date2 - date1);
const res = duration.as('hours');
console.log(`Hours difference: ${res}`);

Output:

Hours difference: 6.5

Manual Calculation Using valueOf

In this approach, the valueOf method is used to get the dates in milliseconds since the Unix epoch. The difference between the two dates is calculated in milliseconds, which is then converted to hours by dividing by the number of milliseconds in an hour.

Syntax:

const res = (date2.valueOf() - date1.valueOf()) / (1000 * 60 * 60);

Example: The below example uses Manual Calculation Using valueOf to Get hours difference between two dates in Moment Js

JavaScript
// script.js
const moment = require('moment');
const date1 = moment('2024-07-24T08:00:00');
const date2 = moment('2024-07-24T14:30:00');
const millisecondsDifference = date2.valueOf() - date1.valueOf();
const res = millisecondsDifference / (1000 * 60 * 60);
console.log(`Hours difference: ${res}`);

Output:

Hours difference: 6.5

Next Article

Similar Reads