handle php date and time

Asked

Viewed 160 times

3

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

I want that when a post is less than an hour apart, it returns to me only minutes, for example:

  • in the database the date the post was pulped is saved as: (2018-01-10 16:02:17)
  • are now: 2018-01-10 16:05:17
  • the return would be: 2018-01-10 00:03:00, that is, 3 minutes apart

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

I tried this code here but failed, returns nothing.

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";
    }

}

1 answer

4


Fox see if that’s what you want code for:

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);
  • Exactly that, thank you :D

Browser other questions tagged

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