frEasyTimeAgo.js
1.7 KB
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
angular.module('fr.frEasyTimeAgo', []).directive('frEasyTimeAgo', [function () {
return {
template: function (elem, attr) {
const MONTH_NAMES = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
];
function timeAgo(dateStr) {
// This is to handle situations when date is not a date but some
// arbitrary string, like "sticky".
if (isNaN(Date.parse(dateStr))) {
return dateStr;
}
const date = new Date(dateStr);
const today = new Date();
const minutes = Math.ceil((today.getTime() - date.getTime()) / 60000);
const hours = Math.round(minutes / 60);
date.setHours(0, 0, 0, 0);
today.setHours(0, 0, 0, 0);
// Must floor it here to account for daylight saving where one
// day won't be equal to 24 hours.
const days = Math.floor((today.getTime() - date.getTime()) / (1000 * 60 * 60 * 24));
if (days === 0 && hours < 1 && minutes > 0) {
return `${minutes} minute${minutes > 1 ? 's' : ''} ago`;
}
if (days === 0 && hours < 24 && minutes > 0) {
return `${hours} hour${hours > 1 ? 's' : ''} ago`;
}
if (days < 4 && minutes > 0) {
return `${days} day${days > 1 ? 's' : ''} ago`;
}
return date.getDate() + ' ' + MONTH_NAMES[date.getMonth()] + ', ' + date.getFullYear();
}
return timeAgo(attr.date);
},
};
}]);