Open In App

How to Get time Difference Between Datetimes in MomentJS?

Last Updated : 26 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

MomentJS is a popular JavaScript library used for parsing, validating, manipulating, and formatting dates. One common requirement when working with dates is calculating the difference between two date times.

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

npm i moment

These are the following approaches:

Using the diff() method

In this approach, we are using the diff() method. diff method is the most straightforward way to get the difference between two datetimes in MomentJS. It calculates the difference in milliseconds by default but can be customized to return the difference in other units.

Syntax:

moment(datetime1).diff(moment(datetime2), unit, precise);

Where-

  • datetime1: The first datetime.
  • datetime2: The second datetime to compare against the first.
  • unit: The unit of measurement (optional, e.g., 'days', 'hours', 'minutes', 'seconds').
  • precise: Boolean to return a precise difference (optional).

Example: In the below example we have used the diff method to get the difference between datetimes.

JavaScript
// Difference in milliseconds
const moment = require('moment');

let datetime1 = moment('2024-07-25T12:00:00');
let datetime2 = moment('2024-07-25T10:00:00');
let diffInMillis = datetime1.diff(datetime2);
console.log(`Difference in milliseconds: ${diffInMillis}`);

// Difference in hours
let diffInHours = datetime1.diff(datetime2, 'hours');
console.log(`Difference in hours: ${diffInHours}`);

Output:

Difference in milliseconds: 7200000
Difference in hours: 2

Using from() and fromNow() method

In this approach we will use from() and fromNow() method. MomentJS provides this methods to display the time difference between two datetimes in a human-readable format. These methods make it easy to present date differences in a more intuitive way, such as "2 hours ago" or "in 3 days."

Syntax:

moment(datetime1).from(moment(datetime2));
moment(datetime1).fromNow();

Example: In below example we will use from and fromNow methods to get difference between datetimes.

JavaScript
const moment = require('moment');
let datetime1 = moment('2024-07-25T12:00:00');
let datetime2 = moment('2024-07-25T10:00:00');
let humanReadableDiff = datetime1.from(datetime2);
console.log(humanReadableDiff);

let datetimeNow = moment();
let datetimeFuture = moment().add(2, 'hours');
let humanReadableDiffNow = datetimeFuture.fromNow();
console.log(humanReadableDiffNow);

Output:

in 2 hours
in 2 hours

Next Article

Similar Reads