Skip to content

MomentJS - Durations

Modern Date/Time: Durations with Moment.js

Section titled “Modern Date/Time: Durations with Moment.js”

Handling lengths of time, or ‘durations’, is a common task in applications, like calculating subscription periods or task completion times. Moment.js provides a dedicated duration object to manage these time spans effectively.

While Moment.js simplifies duration handling, remember it’s in maintenance mode. For new projects, consider alternatives like Day.js or date-fns which often offer better performance and smaller bundle sizes. See the ‘Overview’ section for more details.

You can create durations in several ways:

  • From a number and unit: moment.duration(100, 'milliseconds'), moment.duration(2, 'hours')
  • From an object: moment.duration({ seconds: 2, minutes: 2, hours: 2, days: 2, weeks: 2, months: 2, years: 2 })
  • From an ISO 8601 duration string: moment.duration('P1Y2M3DT4H5M6S')
  • From the difference between two moments: const duration = moment.duration(endMoment.diff(startMoment));

Once you have a duration object, you can manipulate and query it using various methods:

Method CategoryExample Syntax
Creatingmoment.duration(Number, String);
moment.duration(Object);
moment.duration(String);
Cloning (Important for Immutability)const newDuration = originalDuration.clone();
Humanizing (Readable Format)duration.humanize(); // e.g., ‘a few seconds’, ‘2 hours’
Getting Total Length (as specific units)duration.asMilliseconds();
duration.asSeconds();
duration.asMinutes();
duration.asHours();
duration.asDays();
duration.asWeeks();
duration.asMonths();
duration.asYears();
Getting Unit Values (within the duration breakdown)duration.milliseconds(); // 0-999
duration.seconds(); // 0-59
duration.minutes(); // 0-59
duration.hours(); // 0-23
duration.days(); // 0-30 (approx)
duration.weeks(); // (derived)
duration.months(); // 0-11
duration.years();
Adding Timeduration.add(500, ‘ms’);
duration.add({ hours: 1, minutes: 30 });
duration.add(anotherDuration);
Subtracting Timeduration.subtract(1, ‘day’);
duration.subtract({ seconds: 10 });
duration.subtract(anotherDuration);
Getting Specific Unit (alias for unit value getters)duration.get(‘hours’); // Equivalent to duration.hours()
Converting to ISO 8601 Stringduration.toISOString(); // e.g., ‘PT1H30M’
Converting to JSON (Serialization)duration.toJSON(); // Returns ISO 8601 string
Checking Typemoment.isDuration(obj); // Returns true if obj is a Moment Duration
Localizationduration.locale(String); // Set locale for humanize output
duration.locale(); // Get current locale
const startTime = moment('2023-10-26T09:00:00');
const endTime = moment('2023-10-26T11:25:30');
// Calculate the difference
const taskDuration = moment.duration(endTime.diff(startTime));
// Display in a human-readable format
console.log(`Task took approximately ${taskDuration.humanize()}.`); // Output: Task took approximately 2 hours.
// Get the precise duration in minutes
console.log(`Precise duration: ${taskDuration.asMinutes()} minutes.`); // Output: Precise duration: 145.5 minutes.
// Get component values
console.log(`Hours: ${taskDuration.hours()}, Minutes: ${taskDuration.minutes()}, Seconds: ${taskDuration.seconds()}`); // Output: Hours: 2, Minutes: 25, Seconds: 30

This demonstrates how durations can represent time differences and be displayed or analyzed in various formats.

For more complex duration formatting (e.g., ‘HH:mm:ss’), you might need the moment-duration-format plugin (check its maintenance status) or use custom formatting logic.

Refer to the official Moment.js documentation for detailed API information: https://momentjs.com/docs/#/durations/