Skip to content

Instantly share code, notes, and snippets.

@biswajitpanday
Created May 31, 2018 09:59
Show Gist options
  • Save biswajitpanday/6a1522debaba26f28039bf5a1e3addb0 to your computer and use it in GitHub Desktop.
Save biswajitpanday/6a1522debaba26f28039bf5a1e3addb0 to your computer and use it in GitHub Desktop.
Fully customizable today, yesterday and date filter in angularjs.
.filter("timeago", function ($filter) {
//time: the time
//local: compared to what time? default: now
return function (time, local) {
if (!time)
return "never";
if (!local)
(local = Date.now())
if (angular.isDate(time))
time = time.getTime();
else if (typeof time === "string")
time = new Date(time).getTime();
if (angular.isDate(local))
local = local.getTime();
else if (typeof local === "string")
local = new Date(local).getTime();
if (typeof time !== 'number' || typeof local !== 'number')
return;
var today = new Date().setHours(0,0,0,0);
var yesterday = new Date(Date.now() - 86400000).setHours(0,0,0,0);
var offset = Math.abs((local - time) / 1000),
span = [],
HOUR = 3600;
if (offset < ((HOUR * 24) - 1) && time > today) span = [ 'today at', $filter('date')(time, 'HH:mm')];
else if (offset < (HOUR * 24 * 2) - 1 && time > yesterday) span = [ 'yesterday at', $filter('date')(time, 'HH:mm')];
else span = [ '', $filter('date')(time, 'MMM dd HH:mm')]
span = span.join(' ');
return span;
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment