treat date and time php [duplicate]

3

I'm developing a posts system, where in the footer of each is displayed the moment the post was published. For this, I use diff to calculate the difference between the current date and the date the post was published.

I want that, when a post has less than an hour difference, it returns to min only the minutes, for example:

  • In the database the date the post was clicked is saved as: ( 2018-01-10 16:02:17 )
  • now they are: 2018-01-10 16:05:17
  • The return would be: 2018-01-10 00:03:00 , that is, 3 minutes of difference

But I want it to return to me only the minutes, because the hours and seconds are 00, and the same thing happens with the hours, if it is greater than 00, that is more than 1 hour of difference, it returns only the hours, in case 01.

I tried this code here but it failed, it does not return anything.

function DateTime($date){
    $dated = date('Y-m-d H:i:s');
    $data1 = new DateTime( $dated );
    $data2 = new DateTime( $date );

    $intervalo = $data1->diff( $data2 );

    if (($intervalo->h) == "0") {
        return $intervalo->i ." Minutos atrás";
    }else{
        return $intervalo->h ." Horas atrás";
    }

    if (($intervalo->i) == "0") {
        return "Agora mesmo";
    }

}
    
asked by anonymous 10.01.2018 / 20:36

1 answer

4

Fox sees if that's what you want code:

function cal_data($date1, $date2){

$dateS1 = new \DateTime($date1);
$dateS2 = new \DateTime($date2);

$dateDiff = $dateS1->diff($dateS2);

if ($dateDiff->h == 0) {
  $result = $dateDiff->i . ' minutos';
} else {
  $result = $dateDiff->h . ' horas e ' . $dateDiff->i . ' minutos';
}

echo $result;

}

$date1='2018-01-09 16:14:01';
$date2='2018-01-09 17:30:04';

cal_data($date1, $date2);
    
10.01.2018 / 20:42