How to format 'angular-moment's 'am-time-ago' directive?
Asked Answered
S

2

8

LIVE DEMO

I use the am-time-ago directive to show a relative timestamp:

<span am-time-ago="publishedAt"></span>

By default, it is formatted as "a day ago", "5 days ago", etc.

How could I change the formatting to be "1d", "5d", "3h", etc?

Salverform answered 9/4, 2014 at 13:52 Comment(0)
M
24

You could customize humanize, somewhere in your config or app start.

moment.lang('en', {
    relativeTime : {
        future: "in %s",
        past:   "%s ago",
        s:  "%d seconds",
        m:  "1m",
        mm: "%dm",
        h:  "1h",
        hh: "%dh",
        d:  "1d",
        dd: "%dd",
        M:  "1m",
        MM: "%dm",
        y:  "1y",
        yy: "%dy"
    }
});

x = new moment();
z = x.clone().add('hours',1);
x.from(z, false);
>> 1h ago
x.from(z, true) //no ago
>> 1h

Docs on realtiveTime

Example: http://jsbin.com/satohazu/1/edit

Mountford answered 9/4, 2014 at 14:11 Comment(9)
Thank for that! In case of "3 months" or "2 years", is that possible to format it using days, e.g. "90d" or "730d"?Salverform
This doesn't have the correct syntax for every measure. For instance mm: "%m" should be mm: "%dm".Choosey
Any ideas how to set two different langs (I mean formats for minutes/seconds etc) for different controllers? In other words, In one box I need to display: 20 minutes ago, but in the second box, 20 min.Shoreward
@Choosey I updated the above but its just an example of how to remap. Feel free to update them to whatever you want.Mountford
@SebastianBochan I could recommend a hack (define an "abbreviated" locale) but i dont know of how to format timeago out of the box.Mountford
Do you mean part with clone() and from() ?Shoreward
Has anyone used this in an Ionic project? can't seem the get dates to format properly, as they just revert back the original "A few seconds ago" format.Cease
@MishaMoroshko Yes 90d instead of 3m (months) can apparently be "configured" as shown here: github.com/urish/angular-moment/issues/44#issuecomment-40210140Stature
I all languages are required then this might be an option: github.com/catamphetamine/javascript-time-agoChristcross
Y
0

The accepted answer by Nix works, but is deprecated by now. Anybody who stumbles across this discussion (like I did) should use moment.updateLocale(locale).

moment.updateLocale('en', {
    relativeTime : {
        future: "in %s",
        past:   "%s ago",
        s:  "%d seconds",
        m:  "1m",
        mm: "%dm",
        h:  "1h",
        hh: "%dh",
        d:  "1d",
        dd: "%dd",
        M:  "1m",
        MM: "%dm",
        y:  "1y",
        yy: "%dy"
    }
});

Details at https://momentjs.com/docs/#/customization/relative-time/

Yaekoyael answered 9/11, 2018 at 11:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.