How to format php date, to display 'Today at 00:00' and 'Yesterday at 00:00'?

Asked

Viewed 745 times

1

I have a record in the TIMESTAMP database and wanted to display for example:

  • If the date is current, show: 'Today at 00:00'
  • If it’s yesterday’s date in the bank, display 'Yesterday at 00:00'
  • And if it is more than 1 day ago, display the day normally, '08/06/2017 at 00:00'
$topico_date = date('Y-m-d H:i:s');  
$exibir = date('d/m/Y H:i:s', strtotime($topico_date);//Exibe: 08/06/2017 17:00:15 

As the date is today I wanted it to display: Today at 5:00

  • 1

    Hello, could you please share 3 examples. Also the timestamp code and what should look like a "from -> to"?

  • 1

    Usually this is done by Javascript - because PHP would process the information only once, but time keeps moving on from there.

  • I edited the post, look there

2 answers

5


There are some ways to deal with this situation. I’m going to explain here a simple way:

<?php
    function converterData($data){
        $dInicio = new DateTime($data);
        $dFim  = new DateTime();
        $dDiff = $dInicio->diff($dFim);
        $dias = $dDiff->days;

        if($dias <= 0) {
            return 'Hoje às ' . $dInicio->format('H:i');
        } else if($dias == 1) {
            return 'Ontem às ' . $dInicio->format('H:i');
        }

        return $dInicio->format('d/m/Y') . ' às ' . $dInicio->format('H:i');
    }

    $topico_date = date('Y-m-d H:i:s'); // Será armazenado 2017-06-08 17:12:32 por exemplo
    echo converterData($topico_date); // Irá imprimir Hoje às 17:12
?>

Using the converterData function, you will get the desired value.

Note that for the above code to work you must have a version of PHP5 greater than or equal to 5.3.0 or the version PHP7.

Reference: PHP: Datetime::diff - Manual

  • you can use only one if and else, the third Return does not need to be within a condition. :)

-1

You can capture the difference between days and check if it is >1, 1 or 0, being:

> 1: days that have passed (difference)

1: A day apart (yesterday)

0: Today

$today = new DateTime('2017-06-08'); // Com timestamp a hora sera incluida
$days = new DateTime('2017-06-08');

$interval = $today->diff($days)->format('%a');
$hour = $today->diff($days)->format('%H:%i:%s');


echo $interval == 0 ? "Hoje às {$hour}" : 
    ($interval == 1 ? "Ontem às {$hour}" : 
    "{$interval} dias atrás");

//Resultado: Hoje às...
  • the following test: http://ideone.com/0freXr

Browser other questions tagged

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