There is no built-in momentjs function to get ['AM', 'PM']
localized, if you look at Accessing locale specific functionality section of the docs, you will see that moment has isPM
and meridiem
:
localeData = moment.localeData()
// ...
localeData.isPM(amPmString); // returns true iff amPmString represents PM
localeData.meridiem(hours, minutes, isLower); // returns am/pm string for particular time-of-day in upper/lower case
// ...
Have a look at Customize#AM/PM and Customize#AM/PM Parsing sections to have further info on how moment manages meridiem.
For most of the locales you can write your own workaround function like this one (using moment(Object)
, format()
and locale()
):
function period(locale) {
return [
moment({h: 0}).locale(locale).format('A'),
moment({h: 23}).locale(locale).format('A')
];
}
['en', 'en-us', 'de', 'it', 'fr', 'zh-cn'].forEach(localeName => {
console.log( localeName, period(localeName) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>
If you nee to manage also locales that have multiple AM/PM values (e.g. zh-cn
), you can use something like the following:
function period(locale) {
const result = new Set();
let m = moment({h: 0}).locale(locale);
for(let i=0; i<24; i++) {
result.add( m.format('A') );
m.add(1, 'h');
}
return Array.from(result);
}
['en', 'en-us', 'de', 'it', 'fr', 'zh-cn'].forEach(localeName => {
console.log( localeName, period(localeName) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>
If you consider using other libraries, note that Luxon (momentjs "younger brother") has the Info.meridiems()
method that may help you, even if seem to handle always 2 values for AM/PM (See zh-cn
result):
const Info = luxon.Info;
['en', 'en-us', 'de', 'it', 'fr', 'zh-cn'].forEach(localeName => {
console.log( localeName, Info.meridiems({ locale: localeName }) );
});
<script src="https://cdn.jsdelivr.net/npm/luxon@1.16.0/build/global/luxon.min.js"></script>