Skip to content

Instantly share code, notes, and snippets.

@tobsn
Created June 19, 2011 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobsn/1034008 to your computer and use it in GitHub Desktop.
Save tobsn/1034008 to your computer and use it in GitHub Desktop.
seconds to fancy time
function s2t(s){
var u=[{n:'now',l:5},{n:'second',l:60,is:1},{n:'minute',l:3600,is:60},{n:'hour',l:86400,is:3600},{n:'yesterday',l:172800,po:true},{n:'tomorrow',l:172800,fo:true},{n:'day',l:604800,is:86400},{n:'week',l:2629743,is:604800},{n:'month',l:31556926,is:2629743},{n:'year',l:Infinity,is:31556926}],
l={'future_format':'%s %t','past_format':'%t %s','second':'second','seconds':'seconds','minute':'minute','minutes':'minutes','hour':'hour','hours':'hours','day':'day','days':'days','week':'week','weeks':'weeks','month':'month','months':'months','year':'year','years':'years','yesterday':'yesterday','tomorrow':'tomorrow','now':'justnow','ago':'ago','in':'in'},
_=function(s,v){if(!isNaN(v)&&v!=1){s=s+'s';}log(l[s]);return l[s]||s;},
m=s.match(/(\d{4,})(?:-(\d{1,2})(?:-(\d{1,2})(?:[T ](\d{1,2}):(\d{1,2})(?::(\d{1,2})(?:\.(\d+))?)?(?:(Z)|([+-])(\d{1,2})(?::(\d{1,2}))?)?)?)?)?/),
a=Date.UTC(m[1],parseInt(m[2]),parseInt(m[3]),parseInt(m[4]),parseInt(m[5]),parseInt(m[6]),0),
d=new Date(),lt=d.getTime(),lo=d.getTimezoneOffset()*60000,tc=lt+lo,d=(a-tc)/10000,da=Math.abs(d);
for(var i in u){
m=u[i];if((m.po&&d<0)||(m.fo&&d>0)){continue;}
if(da<m.l){if(isNaN(m.is)){return _(m.n,NaN);}
a=da/m.is;a=Math.round(a);
if(d < 0){lt=_('future_format',NaN).replace('%s',_('in',NaN));}else{lt=_('past_format',NaN).replace('%s',_('ago',NaN));}
return lt.replace('%t',a+' '+_(m.n,a));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment