How do I get how long ago was a news post, e.x.: 30 minutes ago, in php?

Asked

Viewed 763 times

1

Would be right?

<?php 
  dateTime();
?>

From my Google searches, I haven’t found a valid answer yet.

  • You can use the date_diff function to compare the date of publication with the current date, if you can post a simple example of your code it would be easier to explain.

  • 1

    Do you want to display this information in a friendly format (like "posted 30 minutes ago"), or do you want to do calculations with it? How the posting date is stored in your database?

  • Hello, Anderson B. Furlan. Good tip, I’ll try to make it work. Thanks. bfavaretto, my intention is this same.

1 answer

2

Using the time() strtotime() functions and comparing the dates, you can do it as follows:

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

Source

Browser other questions tagged

You are not signed in. Login or sign up in order to post.