How to format date php, to display 'Hojé as 00:00' and 'Yesterday as 00:00'?

0

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 yesterday's date is in the database, view '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 17:00

    
asked by anonymous 08.06.2017 / 21:53

2 answers

4

There are some ways to deal with this situation. Here is 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 convertData function, you will get the desired value.

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

Reference: PHP: DateTime :: diff - Manual

    
08.06.2017 / 22:12
-1

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

> 1 : days that have passed (difference)

1: One day difference (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...
    
08.06.2017 / 22:34