gwar9 gwar9 - 4 months ago 55
AngularJS Question

Format longDateFormat in Moment.js

I asked an earlier question about formatting AM/PM via Moment.js meridiem function. BTW I am using version 2.9

I was successful in adding periods to the AM/PM input and applying lowercase by using the this

moment.locale('en', {
meridiem: function(hour, minute, isLower) {
if (hour < 12) {
return isLower ? 'a.m.' : 'A.M.';
} else {
return isLower ? 'p.m' : 'P.M.';
}
}
});


Now I have run into an issue where I need to do the same type of formatting for a
longDateFormat
string.

The string is
"h:mm:ss a"
and the time returned would be the current time but with an uppercase AM/PM

I need the current time returned but the a input should be formatted a.m. p.m.

in the moment docs longDateFormat is an object not a function how would I go about formatting the meridiem here?

********************EDIT****************

Here is an example of my issue.

the meridiem setting is working fine with an h a z input. it is lowercase and has periods.
enter image description here

the meridiem setting doesn't affect a longDateFormat string. The am/pm is always uppercase with no periods. No matter if I change the meridiem settings I applied initially. How can I change this?

HTML
enter image description here

{{last_update|date:"MMMM d, y 'at' h:mm:ss a"}}.


Result
enter image description here

Last updated on July 6, 2016 at 8:25:00 AM.


Thanks

Answer

Since you are using angular, you have to use angular-moment to take advantage of moment inside directive and filters.

angular-moment provides a amDateFormat filter that Format dates using moment.js format() method as the docs say. The following code can help to get what you desire:

angular.module('MyApp',['angularMoment'])
.run(function(){
  moment.locale('en', {
    meridiem: function(hour, minute, isLower) {
      if (hour < 12) {
         return isLower ? 'a.m.' : 'A.M.';
      } else {
         return isLower ? 'p.m.' : 'P.M.';
      }
    }
  });
})
.controller('AppCtrl', function($scope) {
  $scope.last_update = new Date();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-moment/0.10.3/angular-moment.min.js"></script>

<div ng-app="MyApp" ng-controller="AppCtrl">
  With angular default date filter: <br/>
  {{last_update|date:"MMMM d, y 'at' h:mm:ss a"}}
  <br/>
  With angular-moment date filter: <br/>
  {{last_update|amDateFormat:'dddd, MMMM Do YYYY, h:mm:ss a'}}
  
</div>

In your example you are using angular default date filter.

Comments