Open In App

Moment.js Customize AM/PM

Last Updated : 20 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to customize the AM/PM logic in Moment.js. The meridiem callback function can be used for customizing the meridiem as per locale. It returns the AM/PM string based on the logic of the callback function.

Syntax:

moment.updateLocale('en', {
    meridiem: Function
});

The below example will help to demonstrate the customization of AM/PM in Moment.js.

Example 1:

Javascript




const moment = require('moment');
 
moment.updateLocale('en', {
 
    // Specify the callback function for
    // customizing the values
    meridiem: function (hour, minute, isLowercase) {
        if (hour >= 12)
            return isLowercase ? 'p.m.' : 'P.M.';
        else
            return isLowercase ? 'a.m.' : 'A.M.';
    }
});
 
console.log(moment().hour(13).format('HH:mm A'));


Output:

13:05 P.M.

Example 2:

Javascript




const moment = require('moment');
 
let localeData = moment.updateLocale('fr', {
    meridiem: function (hours, minutes, isLower) {
        return hours < 12 ? 'PD' : 'MD';
    }
});
 
var m = moment('2022-08-15T20:00:00').format('hh a');
console.log("Customized AM/PM is :", m);


Output: 

Customized AM/PM is : 08 MD

Reference: https://momentjs.com/docs/#/customization/am-pm/ 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads