Trouble using moment.js date formatting lib


#1

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


#2

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>

#3

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.


#4

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

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


#5

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.


#6

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