AngularJS “Ago” Coffee Filter

Just made a jam-packed and ugly AngularJS filter that converts a date to an “ago” string. So if you entered a javascript date it will convert it to “10 days ago” or “23 minutes ago”. Short hand, and in-line function, yes it’s messy, but interesting!

ng = angular.module "myApp", []
ng = ng.filter "ago", () -> (dt) -> 
  if not dt then return ''
  agofn = (val,unit)-> return val + ' '+unit+(if val>0 then 's')+' ago'
  msecs = (new Date()).getTime()-(new Date(dt)).getTime() 
  days = parseInt(msecs/(24*60*60*1000))
  if days>0 then return agofn days, 'day'
  hours = parseInt(msecs/(60*60*1000))
  if hours>0 then return agofn hours, 'hour'
  mins = parseInt(msecs/(60*1000))  
  if mins>0 then return agofn mins, 'minute'
  secs = parseInt(msecs/1000)
  return agofn secs,'second'

Here’s how you would use it:

I ran {{myDate | ago}} ...

This is what it will output:

I ran 45 minutes ago ...

Here is my GIST for the same code.

Comments are closed.