Moment.js moment.duration().humanize() Method
The moment().duration().humanize() Method is used to return the length of the duration in a human-readable format. The text returned is suffix-less by default, however, suffixes can also be added by specifying the withSuffix parameter. This can also be used for denoting past time by using negative durations.
Syntax:
moment().duration().humanize(withSuffix, thresholds);
Parameters: This method accepts two parameters as mentioned above and described below:
- withSuffix: This is a Boolean value that can be used to specify if the returned time will include a suffix. It is an optional parameter.
- thresholds: It is an optional parameter.
Return Value: This method returns a string that denotes the duration in a human-readable format.
Note: This will not work in the normal Node.js program because it requires an external moment.js library to be installed globally or in the project directory.
Moment.js can be installed using the following command:
Installation of moment module:
npm install moment
Example 1: The below examples will demonstrate the Moment.js moment.duration().humanize() Method.
- Filename: index.js
Javascript
const moment = require( 'moment' ); let durationOne = moment.duration(9, 'months' ) console.log( "The humanized version of durationOne is:" , durationOne.humanize() ); // Using the withSuffix property let durationTwo = moment.duration(5, 'hours' ) console.log( "The humanized version of durationTwo is:" , durationTwo.humanize( true ) ); |
Steps to run the application: Write the below command in the terminal to run the index.js file:
node index.js
Output:
The humanized version of durationOne is: 9 months The humanized version of durationTwo is: in 5 hours
Example 2:
Javascript
const moment = require( 'moment' ); // Changing of locale let durationThree = moment.duration(9, 'months' ).locale( 'es' ); console.log( "The humanized version of durationThree is:" , durationThree.humanize() ); // Changing of locale with suffix let durationFour = moment.duration(9, 'months' ).locale( 'es' ); console.log( "The humanized version of durationFour is:" , durationFour.humanize() ); // Using a negative duration let durationFive = moment.duration(-5, 'days' ) console.log( "The humanized version of durationFive is:" , durationFive.humanize( true ) ); |
Output:
The humanized version of durationThree is: 9 meses The humanized version of durationFour is: 9 meses The humanized version of durationFive is: 5 days ago
Reference: https://momentjs.com/docs/#/durations/humanize/