Open In App

Moment.js moment.duration().locale() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The moment().duration().locale() Method is used to return or set the locale of the duration. The locale of a duration will also affect methods like humanize() method that return the time in text, where different locales will affect the language of the text.

Syntax:

moment().duration().locale(String)

Parameters: This method accepts a single parameter as mentioned above and described below:

  • String: This will be the string that specifies the locale that has to be applied.

Return Value: It returns the current locale of the Duration.

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

The below examples will demonstrate the Moment.js moment.duration().locale() Method.

Example 1:

Javascript




const moment = require('moment');
  
// Get current locale
let durationOne = moment.duration(9, 'months');
console.log(
    "The locale of durationOne is:",
 durationOne.locale()
);
console.log(
    "The humanized version of durationOne is:",
 durationOne.humanize()
);
  
// Set locale to 'es'
let durationTwo = 
    moment.duration(9, 'months').locale('es');
console.log(
    "The humanized version of durationTwo is:",
 durationTwo.humanize()
);
  
// Set locale to 'it'
let durationThree = 
    moment.duration(9, 'months').locale('it');
console.log(
    "The humanized version of durationThree is:",
 durationThree.humanize()
);


Output:

The locale of durationOne is: en
The humanized version of durationOne is: 9 months
The humanized version of durationTwo is: 9 meses
The humanized version of durationThree is: 9 mesi

Example 2:

Javascript




const moment = require('moment');
  
// Get current locale
let durationA = moment.duration(9, 'months');
console.log(
    "The humanized version of durationA is:",
 durationA.humanize()
);
  
// Set locale to 'es'
let durationB = moment.duration(9, 'months').locale('es');
console.log(
    "The humanized version of durationB is:",
 durationB.humanize()
);
  
// Set locale to 'it'
let durationC = moment.duration(9, 'months').locale('it');
console.log(
    "The humanized version of durationC is:",
 durationC.humanize()
);


Output:

The humanized version of durationA is: 9 months
The humanized version of durationB is: 9 meses
The humanized version of durationC is: 9 mesi

Reference: https://momentjs.com/docs/#/durations/locale/



Last Updated : 18 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads