Skip to content

Instantly share code, notes, and snippets.

@ricardobeat
Created December 10, 2010 16:22
Show Gist options
  • Save ricardobeat/736412 to your computer and use it in GitHub Desktop.
Save ricardobeat/736412 to your computer and use it in GitHub Desktop.
tempo relativo / relative time
function tempoRelativo(_date, showSeconds){
// offset a partir da data atual em segundos
var s = ~~( (+new Date-Date.parse(_date)) / 1000 );
// encontrar unidade de tempo
var un = (s<60) ? 'segundo'
: (s /= 60)<60 ? 'minuto'
: (s /= 60)<24 ? 'hora'
: (s /= 24)<30.4 ? 'dia'
: (s /= 30.4)<365 ? 'mes'
: 'ano';
// plurais
un += ((s=~~s)>1 || s==0) ? (un == 'mes' ? 'es' : 's') : '';
return !showSeconds && ~un.indexOf('segundo')
? 'menos de um minuto atrás' // se showSeconds == true -> x segundos atrás
: s+' '+un+' atrás';
};
// var t = "Fri Oct 01 2010 14:15:00 GMT-0300 (BRT)";
// tempoRelativo(t) => "x horas atrás";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment