How to get the meridian (am / pm) with momentsjs and angularjs

You could also do something like m.format('a')


A few things:

  • The word you're looking for is "meridiem", not "meridian". It's a Latin word meaning "mid-day". A.M. is "ante meridiem" (before mid-day) and P.M. is "post meridiem" (after mid-day).

  • The .hours() function and the input array passed to the moment constructor both expect hours of a 24-hour clock, from 0 to 23. There is no built-in function to accept or output a 12-hour clock value, or a meridiem (am/pm).

  • The parsing and formatting functions in moment do have options for 12-hour clock hours (h or hh) and meridiem (A or a), but you're not parsing or formatting in your use case, so they would be a bit clumsy to use. In particular, they are based on moment's current locale settings, so testing a string would be problematic if the locale wasn't fixed to a specific language.

  • You can use these simple functions to convert from 12-hour + meridiem to 24-hour and vice-versa. They are not specific to moment, so you can also use them with the Date object or elsewhere.

    function hours12to24(h, pm) {
        return h == 12 ? pm ? 12 : 0 : pm ? h + 12 : h;
    }
    
    function hours24to12(h) {
        return {
            hour : (h + 11) % 12 + 1,
            pm : h >= 12
        }
    }
    

    To test these functions:

    function test() {
      for (var i = 0; i <= 23; i++) {
        var x = hours24to12(i);
        var h = hours12to24(x.hour, x.pm);
        console.log(i + " == " + x.hour + (x.pm ? " pm" : " am") + " == " + h);
      }
    }
    
  • Also, be careful when calling .month() to get the month number, the results are 0-11, not 1-12. The same is true when building the input array. Your dropdown either needs to use 0-11, or you need to add or subtract 1 accordingly.