How do I pick up how long ago a news article was published, e.x .: 30 minutes ago in php?

1

Would it be the right one?

<?php 
  dateTime();
?>

By searching for Google, I still have not found a valid answer.

    
asked by anonymous 17.04.2014 / 16:46

1 answer

2

Using the time () strtotime () functions and comparing the dates, you can do the following:

class Data {

public static function ExibirTempoDecorrido($date)
{
    if(empty($date))
    {
        return "Informe a data";
    }

    $periodos = array("segundo", "minuto", "hora", "dia", "semana", "mês", "ano", "década");
    $duracao = array("60","60","24","7","4.35","12","10");

    $agora = time();
    $unix_data = strtotime($date);

    // check validity of date
    if(empty($unix_data))
    {  
        return "Bad date";
    }

    // is it future date or past date
    if($agora > $unix_data) 
    {  
        $diferenca     = $agora - $unix_data;
        $tempo         = "atrás";
    } 
    else 
    {
        $diferenca     = $unix_data - $agora;
        $tempo         = "agora";
    }

    for($j = 0; $diferenca >= $duracao[$j] && $j < count($duracao)-1; $j++) 
    {
        $diferenca /= $duracao[$j];
    }

    $diferenca = round($diferenca);

    if($diferenca != 1) 
    {
        $periodos[$j].= "s";
    }

    return "$diferenca $periodos[$j] {$tempo}";
}
}

Calling the function:

print_r(Data::ExibirTempoDecorrido(date("12/31/2010")));

You'll get the result:

3 anos atrás

Font

    
18.04.2014 / 00:45