Angular filter to show how much time ago from a date object

By: Ryan Wong at

Here’s a good directive I found that formats a date object as time ago string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
function timeago() {
return function(input, p_allowFuture) {

var substitute = function (stringOrFunction, number, strings) {
var string = angular.isFunction(stringOrFunction) ? stringOrFunction(number, dateDifference) : stringOrFunction;
var value = (strings.numbers && strings.numbers[number]) || number;
return string.replace(/%d/i, value);
},
nowTime = (new Date()).getTime(),
date = (new Date(input)).getTime(),
//refreshMillis= 6e4, //A minute
allowFuture = p_allowFuture || false,
strings= {
prefixAgo: '',
prefixFromNow: '',
suffixAgo: "ago",
suffixFromNow: "from now",
seconds: "less than a minute",
minute: "about a minute",
minutes: "%d minutes",
hour: "about an hour",
hours: "about %d hours",
day: "a day",
days: "%d days",
month: "about a month",
months: "%d months",
year: "about a year",
years: "%d years"
},
dateDifference = nowTime - date,
words,
seconds = Math.abs(dateDifference) / 1000,
minutes = seconds / 60,
hours = minutes / 60,
days = hours / 24,
years = days / 365,
separator = strings.wordSeparator === undefined ? " " : strings.wordSeparator,


prefix = strings.prefixAgo,
suffix = strings.suffixAgo;

if (allowFuture) {
if (dateDifference < 0) {
prefix = strings.prefixFromNow;
suffix = strings.suffixFromNow;
}
}

words = seconds < 45 && substitute(strings.seconds, Math.round(seconds), strings) ||
seconds < 90 && substitute(strings.minute, 1, strings) ||
minutes < 45 && substitute(strings.minutes, Math.round(minutes), strings) ||
minutes < 90 && substitute(strings.hour, 1, strings) ||
hours < 24 && substitute(strings.hours, Math.round(hours), strings) ||
hours < 42 && substitute(strings.day, 1, strings) ||
days < 30 && substitute(strings.days, Math.round(days), strings) ||
days < 45 && substitute(strings.month, 1, strings) ||
days < 365 && substitute(strings.months, Math.round(days / 30), strings) ||
years < 1.5 && substitute(strings.year, 1, strings) ||
substitute(strings.years, Math.round(years), strings);
// console.log(prefix+words+suffix+separator);
prefix.replace(/ /g, '')
words.replace(/ /g, '')
suffix.replace(/ /g, '')
return (prefix+' '+words+' '+suffix+' '+separator);

};
};

Hope this helps you out.