Open In App

Moment.js Customize Ordinal Names

Improve
Improve
Like Article
Like
Save
Share
Report

Moment.js is a JavaScript date library for parsing, validating, manipulating, and formatting dates. The ordinals of date values of the Moment output is customizable according to our needs. We will be using the moment.updateLocale() method for this.

Syntax:

moment.updateLocale('en', {
    ordinal: callback_function
});

Parameters: The updateLocale method will accept an object that has the ordinal property that can be used to specify the callback function used for customizing the ordinal names.

 

The default ordinals of the numbers are as follows:

  • 1: st
  • 2: nd
  • 3: rd
  • 4: th
  • 5: th
  • 6: th
  • 7: th
  • 8: th
  • 9: th

Note: This will not work in the normal Node.js program because it requires the moment.js library to be installed.

Moment.js can be installed using the following command:

npm install moment

Example 1:

Javascript




// Acquiring the plugin
var moment = require("moment");
  
// Customizing the ordinal method
var ordinal_name = moment.updateLocale("en", {
    ordinal: function (num) {
        var last_digit = num % 10;
        var ordinal = ~~((num % 100) / 10) === 1
            ? "`th"
            : last_digit === 1
                ? "`st"
                : last_digit === 2
                    ? "`nd"
                    : last_digit === 3
                        ? "`rd"
                        : "`th";
        return num + ordinal;
    },
});
  
console.log("Ordinal name of 3 is:", ordinal_name.ordinal(3));
console.log("Todays Date is:", moment().format('Do'))


Output:

Ordinal name of 3 is: 3`rd
Todays Date is: 13`th

Example 2:

Javascript




// Acquiring the plugin
var moment = require("moment");
  
// Customizing the ordinal method
var ordinal_name = moment.updateLocale("en", {
    ordinal: function (num) {
        var last_digit = num % 10;
        var ordinal = ~~((num % 100) / 10) === 1
            ? "-TH"
            : last_digit === 1
                ? "-ST"
                : last_digit === 2
                    ? "-ND"
                    : last_digit === 3
                        ? "-RD"
                        : "-TH";
        return num + ordinal;
    },
});
  
console.log("Ordinal name of 5 is:", ordinal_name.ordinal(5));
console.log("Todays Date is:", moment().format('Do'))


Output:

Ordinal name of 5 is: 5-TH
Todays Date is: 13-TH

Reference: https://momentjs.com/docs/#/customization/ordinal/



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