Search code examples
angularjsmomentjsangular-directiveangular-moment

moment.js in angular is not formatting as I would expect


I have a Time being pulled from a server in the following JSON format:

"begins_at":"2016-04-22T08:11:07.000Z"

I am using momentjs with angular with the following filter:

{{event_details.begins_at | moment: "format": "HH:MM a"}}

I would expect the following output: 08:11 am. Instead, I am getting: 04:04 am. I suspect it might have something to do with timezones, but I'm not sure. How do I fix this?


Solution

  • Change MM to mm (months to minutes : ))

    angular.module('app', [])
      .provider('moment', function() {  // be nice for DI
        this.$get = function() {
          return moment
        }
      })
      .controller('ctrl', function() {
        this.event_details = {
          begins_at: '2016-04-22T08:11:07.000Z'
        }
      })
      .filter('moment', function(moment) {
        return function(input, options) {
          return moment(input).format(options.split('\'')[1]) // ugly formatter ; (
        }
      })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    
    <div ng-app='app'>
      <div ng-controller='ctrl as c'>
        moment: {{ c.event_details.begins_at | moment:"format: 'HH:mm a'" }}
      </div>
    </div>