![]() |
VOOZH | about |
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.
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.
moment.duration(time).humanize();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 daysMoment.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.
moment.duration(time).humanize({suffix: true});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