VOOZH about

URL: https://www.geeksforgeeks.org/javascript/how-to-full-humanized-durations-in-momentjs/

⇱ How to Full Humanized Durations in MomentJS? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Full Humanized Durations in MomentJS?

Last Updated : 23 Aug, 2024

Managing time and date formats in web development is important for a good user experience. Moment.js is a popular JavaScript library that helps with this by providing tools to format and manipulate dates and times. One key feature is humanizing durations, which turns time spans into more readable formats. For example, instead of showing "600 seconds," it would display "10 minutes." This makes it easier for users to understand how much time has passed or how much time is left.

Humanized duration refers to converting a time duration into a natural language format. For instance, instead of displaying "600 seconds," it would be shown as "10 minutes," or instead of "3,600,000 milliseconds," it would be shown as "an hour." This type of transformation makes it easier for users to comprehend time intervals without needing to mentally convert units.

Approach

Basic Humanization of Durations

This is the simplest way to humanize a duration. This is done by using the humanize() function provided by Moment.js. This function automatically converts a duration into a readable format.

Syntax :

moment.duration(time).humanize();

Parameters:

  • time: This is the duration you want to humanize. It can be specified in milliseconds, seconds, minutes, hours, days, etc.
  • humanize(): It Converts the duration into a human-friendly string.

Example: This code creates a 2-day duration using Moment.js and converts it into a human-readable format, printing "2 days" to the console.

Output:

2 days

Customization of Output

Moment.js allows us to customize how the duration is displayed. For example, assume we want to add "ago" or "from now" to indicate whether the duration is in the past or future.

Syntax:

moment.duration(time).humanize({suffix: true});

Parameters:

  • suffix: Adding {suffix: true} will add "ago" or "from now" to the output based on whether the duration is in the past or future.

Example: This code illustrates a 5-hour future duration as "in 5 hours" and a 3-minute past duration as "3 minutes ago" using Moment.js.

Output:

in 5 hours
3 minutes ago
Comment
Article Tags: