AngularJS date filter with MomentJS

Dates can be extremely complex things to manage in an application, especially if you also need to deal with multiple localizations.

I’ve never come across a date management library as powerful and simple as MomentJS. And so it made perfect sense for me to see how to integrate MomentJS into an AngularJS application.

The best way I could come up with to do this in the most reusable way, is by creating an angular filter:

/* depends on MomentJS being available as a global */
app.filter('dateFormatter', function() {
return function(date, format) {
if(!moment) {
console.log('Error: momentJS is not loaded as a global');
return '!momentJS';
}
moment.locale('de'); //needed if you want to change the locale globally
if(!format) {
return moment(date).fromNow();
} else {
return moment(date).format(format); //in absence of format parameter, return the relative time from the given date
}
}
});

A couple of comments on how this filter works:

  • The date parameter should be an object that allows you to instantiate a moment object directly. In my app, I pass around dates as the date in milliseconds. Checkout the MomentJS documentation to see how moment objects can be instantiated.
  • The format parameter specifies a format for MomentJS to use. For example, if I want to get a date as “22 Oktober”, I will pass the string ‘D MMM’ as the format parameter. MomentJS supports a ton of options for formatting, check them out HERE.

How to use this filter

You typically use an Angular filter within your html with this syntax:

<p>[[[concert.dateInMs | dateFormatter]]]</p>

But the filter syntax allows you to pass arguments as well. I use this feature to pass in the format I wand from the filter, like this:

<p>[[[concert.dateInMs | dateFormatter: ‘D’]]]</p>
<p>[[[concert.dateInMs | dateFormatter: ‘MMM’]]]</p>

And that’s it. Simple, and above all, highly reusable. You can get more fancy with this filter, for example, pass in an object literal as the format parameter instead of the string, in case you want to further customize the output from the filter.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.