简体   繁体   中英

Custom formatting for a time using Moment.js

I'm having difficulty with formatting a time using moment.js . I decided to try out angular-moment and was faced with some limitations, and after looking at the documentation for moment.js , it seems that it would be a lot better to create a custom directive which uses moment . Here lies my problem, I have some experience and knowledge of basic directives, but I'm not sure how to move forward with creating a directive which uses moment to format a date/time. So, here are the rules I want to adhere to:

Less than 1 minute ago: print as a few seconds ago More than 1 minute ago && less than 1 hour ago: print as X minutes ago More than 1 hour ago: print as h:mm a Yesterday (This should compare the two days to see if it is today or yesterday): print as Yesterday More than yesterday: print as MMM DD

So I'm unsure where to start really, and any help is welcome!

Moment.js is the way to go! I recommend you use angular filter instead of directive.

Here is how you might implement one with moment.js fromNow function :

var fromNow = function () {
        return function (value, format) {
            return moment(value).fromNow();
        };
    };

    angular.module('myApp').filter('fromNow', fromNow);

And you simply call it from html:

<span>{{player.activeSince | fromNow}}</span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM