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

Issue

I have a question about the library moments.js, I have an application in angularjs where I have six select elements for the year, month, day, hour, minutes, and am / pm format. I am using the following format moment to build m.format date (‘YYYY-MM-DD hh: mm: ss a).

The code is as follows:

var m = moment([scope.val.year, scope.val.month, scope.val.date, scope.val.hour, scope.val.minute]); //build date 

model.$setViewValue(m.format('YYYY-MM-DD hh:mm:ss a'))

I get the data m.hour (), m.minute (), etc but there is a way to get the am / pm format, I have not found anything about it, something perhaps as m.meridian () => "am "or" pm ".

I would build the array passing as parameter if am or pm, and then also would get from any date if am or pm date.

Solution

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.

Answered By – Matt Johnson-Pint

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published