AngularJs: User friendly date display with AngularJs and MomentJs

Whether you checkout Twitter or any of the other uber popular web apps, you will find dates displayed are often in a very user friendly "from now" format. Examples of this format are "Just now", "A few minutes ago", and "2 days ago". In these three examples a date value is displayed as an approximation of the difference between the absolute date value and the current time. This "from now" format could be applied on the server, but it is generally better to apply this on the client side via javascript so that it can be continually updated to reflect the every passing time. 2 javascript examples I've come across for applying the "from now" format are John Resig's lightweight pretty date library, and the other is more built-out Moment.js. In this post I explain how to apply a sliver of the power of MomentJs in an AngularJs application.
AngularJs is a delightful Client side javascript framework. One of its features is called "filters". Filters can be succinctly applied to a collections or particular values. Here is a quick example of using the built uppercase filter to produce HELLO WORLD.

{{ 'Hello World' | uppercase}}
AngularJs even comes with a built-in date filter which is great for producing typical absolute value date formats, but unfortunately it doesn't come with a "from now" format.

{{ date_expression | date[:format] }}
Lucky for us, creating our own filter is pretty easy once you know how. The following code injects a filter called fromNow into the module myModule.

angular.module('myModule').
  filter('fromNow', function() {
    return function(dateString) {
      return moment(dateString).fromNow()
    };
  });
Now all you need to do is apply this filter in your template, you have your very user friendly date format, just like the big guys!

{{ reply.createdDate | fromNow }}

Comments

  1. Any ideas how to make this display actually update as time passes? reply.createDate naturally does not change, but as time passes the result from moment().fromNow call will change, and I'm not sure what's the most angularish way to implement that.

    ReplyDelete
    Replies
    1. Sorry I'm only seeing this now. It's a good question. Just thinking off the top of my head, I would say you would have to take another tac, and add an additional attribute to the scope - let's call it reply.fromNow - and update that value within the controller periodically using the moment library.

      Delete
  2. This is awesome! Moment also accepts date strings so it's unnecessary to use the Date constructor - can just do moment(dateString).fromNow()

    ReplyDelete
    Replies
    1. Thanks Alex. I'll update my example with this.

      Delete
  3. Very helpful. I only needed to make a small modification to accept unix timestamps instead:
    return moment.unix(dateString).fromNow()

    ReplyDelete
  4. Great work there! Just used this in an app of mine. Echoing Alex Zylman I did take out that date constructor from the return - actually this extra date constructor was breaking it in every browser but chrome for me - taking it out fixed things! :)

    ReplyDelete
  5. Here's another approach that uses a directive and thus is able to keep updating the value as time marches forward. https://github.com/urish/angular-moment

    ReplyDelete
  6. Hi @all.
    i have found a similar filter to show UTC times in angular (also uses moment.js)
    [code]
    // based on http://stackoverflow.com/a/21760213/574981
    // modified by s-light
    // accepts string or date object as input.
    // format with moment.js formating.
    // optional utcOfsset parameter (default = 0)
    app.filter('momentFormatUTCOffset', function() {
    return function(input, format, utcOffset_new) {
    if (!utcOffset_new) {
    utcOffset_new = 0;
    }
    return moment(input).utc().utcOffset(utcOffset_new).format(format);
    };
    });
    [/code]

    ReplyDelete
    Replies
    1. pleas delete this one.. the login system has not worked right...

      Delete
  7. Hi @all.
    i have found a similar filter to show UTC times in angular (also uses moment.js)
    [code]
    // based on http://stackoverflow.com/a/21760213/574981
    // modified by s-light
    // accepts string or date object as input.
    // format with moment.js formating.
    // optional utcOfsset parameter (default = 0)
    app.filter('momentFormatUTCOffset', function() {
    return function(input, format, utcOffset_new) {
    if (!utcOffset_new) {
    utcOffset_new = 0;
    }
    return moment(input).utc().utcOffset(utcOffset_new).format(format);
    };
    });
    [/code]

    ReplyDelete
  8. Hello Eamonn, I have been training students on AngularJS for past 6 months, and at times, I have used your blog as reference for the class training and also for my personal project development. It has been so much useful. Thank you, keep writing more:)
    Shashaa
    AngularJS courses in Chennai

    ReplyDelete
  9. Great explanation with appropriate example. AngularJs minimizes the coding the great extend.
    AngularJs Training
    AngularJs Training in Chennai

    ReplyDelete
  10. Hii author nice post! AngularJs is the best framework which is supported by google! I have personally used angularJs for my previous web app developement project and I'am quite satisfied by the output.
    Angulars training | Angularjs training in Chennai | AngularJs training institute in Chennai

    ReplyDelete
  11. Thanks for posting this useful content, Good to know about new things here, Let me share this,
    AngularJS Training in Chennai | AngularJS Training | Best AngularJS Training Institute in Chennai

    ReplyDelete
  12. Hi, the information you provided here is very informative and useful for me. If anyone interested to learn AngularJS Training reach GangBoard. MSBI Training | Hadoop Training

    ReplyDelete
  13. This topics detail is well done!! Any lesser easy understanding for this blog article post.Very help to for beginners level audience.
    Selenium Training in Chennai

    ReplyDelete
  14. Thanks for sharing your web page. SAS has an incredible breadth in IT industry. It’s an application suite that can change, oversee and recovers information from the assortment of root and perform measurable explanatory on it.
    Regards,
    Best Angularjs Training in Chennai

    AngularJS Training in Chennai

    ReplyDelete
  15. Thanks for sharing this information and keep updating us.This content is really helpful to me.
    AngularJS Training in Chennai | AngularJS Training Chennai | AngularJS Course in Chennai

    ReplyDelete

Post a Comment

Popular posts from this blog

Getting started with Grails functional tests using Geb + Spock

Nerd Tree: A File Explorer with Mac Vim