简体   繁体   中英

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 ampm

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 haz input. it is lowercase and has periods. 在此处输入图片说明

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 在此处输入图片说明

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

Result 在此处输入图片说明

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

Thanks

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 ? 'am' : 'AM'; } else { return isLower ? 'pm' : 'PM'; } } }); }) .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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM