Created
June 11, 2012 21:02
-
-
Save oliveiraev/2912678 to your computer and use it in GitHub Desktop.
Formata de maneira customizada intervalos de data.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
ini_set('date.timezone','America/Sao_Paulo'); | |
class DateFormatter extends DateTime | |
{ | |
private $parts = array( | |
array(31104000, 'ano', 'anos'), | |
array(2592000, 'mês', 'meses'), | |
array(86400, 'dia', 'dias'), | |
array(3600, 'hora', 'horas'), | |
array(60, 'minuto', 'minutos'), | |
array(1, 'segundo', 'segundos'), | |
); | |
public function formattedInterval(DateTime $relativeTo = NULL) | |
{ | |
if (is_null($relativeTo)) { | |
$relativeTo = new DateTime(); | |
} | |
$diff = parent::format('U') - $relativeTo->format('U'); | |
$past = FALSE; | |
if ($diff < 0) { | |
$past = TRUE; | |
$diff *= -1; | |
} | |
foreach ($this->parts as $subparts) { | |
$n = floor($diff / $subparts[0]); | |
if ($n) { | |
$output = '%d %s'; | |
$part = $subparts[$n > 1 ? 2 : 1]; | |
if ($past) { | |
$part .= ' atrás'; | |
} | |
return sprintf($output, $n, $part); | |
} | |
} | |
return 'agora'; | |
} | |
} | |
$d = new DateFormatter('10-May-2011'); | |
var_dump($d->formattedInterval()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment