Skip to content

Instantly share code, notes, and snippets.

@vespoli
Created December 18, 2016 23:38
Show Gist options
  • Save vespoli/6fdf72f8ae66c473f5bed67850f23c6a to your computer and use it in GitHub Desktop.
Save vespoli/6fdf72f8ae66c473f5bed67850f23c6a to your computer and use it in GitHub Desktop.
Time ago filter for Angular
angular
.module('foo', [])
.filter('timeAgo', function() {
return function(s) {
var d = new Date(s);
var seconds = Math.floor((new Date() - d) / 1000);
var interval = Math.floor(seconds / 31536000);
if (interval > 1) {return interval + " years ago";}
if (interval === 1) {return interval + " year ago";}
interval = Math.floor(seconds / 2592000);
if (interval > 1) { return interval + " months ago";}
if (interval === 1) {return interval + " month ago";}
interval = Math.floor(seconds / 86400);
if (interval > 1) {return interval + " days ago";}
if (interval === 1) {return interval + " day ago";}
interval = Math.floor(seconds / 3600);
if (interval > 1) {return interval + " hours ago";}
if (interval === 1) {return interval + " hour ago";}
interval = Math.floor(seconds / 60);
if (interval > 1) {return interval + " minutes ago";}
if (interval === 1) {return interval + " minute ago";}
return Math.floor(seconds) + " seconds ago";
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment