frEasyTimeAgo.js 1.7 KB
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);
        },
    };
}]);