haxxxton haxxxton - 1 month ago 12
Javascript Question

Get list of meridiems in MomentJs

MomentJS allows for multiple languages to be supplied to it in order to create locales for formatting and calculation.

They specifically mention that some languages use more than two meridiems, and that there are functions for returning lists of months/days for a locale. Is there any way to return a list of the meridiems for the current locale?

Short of looping over 24 hours, calling

moment.localeData().meridiem(x)
for each hour and then looking for uniques i cant seem to find any documentation about it. Has anyone found a way to get this list, or is this something that I should request on their github?

Answer

Looks like looping is the only way

let fn = moment().locale('zh-cn').localeData().meridiem,
    meridiems = new Set();
for (let hour = 0; hour < 24; hour++) {
  for (let minute = 0; minute < 60; minute++) {
    // get both upper and lower cases
    meridiems.add(fn(hour, minute, true));
    meridiems.add(fn(hour, minute, false));
  }
}
console.log(Array.from(meridiems.values()));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/locale/zh-cn.js"></script>