Trouble using moment.js date formatting lib

I’m trying to use the moment.js library to format some dates in my app; but I’m unable to get anything working at all. Do I need to write a directive? I really have no idea where to start in hooking this in and I’m getting frustrated trying things that don’t work.

Current view that has unformatted date

<div data-ng-if="thing.date">{{thing.date}}</div>

And all I want to do is format that date in my view

You are going to want to create an Angular filter. Have a look at one of min:

.filter('ago', function() {
  return function(input) {
    m = moment(input)
    if (m.isValid()){
      return m.fromNow();
    } else {
      return input;
    }
  };
})

And you use it by adding the following in your template

<div data-ng-if="thing.date">{{thing.date | ago}}</div>
2 Likes

This is how I do it:

In your html file’s <head> reference the moment library:

<script src="vendor/moment.js"></script>

Then create a filter like to the below:

angular.module('my.filters').filter('friendlyDate', function() {
    	return function(date) {
    		return moment(date).format('MMMM Do YYYY, h:mm:ss a');
    	};
});

Now anywhere you need a formatted date, you can simply do it this way:

<div data-ng-if="thing.date">{{thing.date | friendlyDate}}</div>

Just make sure your filter is visible to your backing controller, hope this helps.

1 Like

I’m assuming you’re aware of Angular’s built-in date filtering functions?

http://docs.angularjs.org/api/ng/filter/date

Excellent, creating a filter(s) worked like a charm.

I was unable to use the built in date functions as I needed to pass single month integers and various other single digits to format specifically on say month: 8 without any additional params.

There is already an angular wrapper for Moment.js, Check this out https://github.com/urish/angular-moment

1 Like