简体   繁体   中英

Calculate the hours minutes and days of difference between two date and hours

I have a PHP and MySQL code that should calculate the hours minutes and days of difference between two date and hours. It works well, just adding 20 hours and 20 minutes more than normal. And I remove the DATE part and put the date and time manually, it works fine.

I don't understand what happens.

    $fecha = $row["fecha"];
        $data= $row["hora"];
$start = strtotime("$fecha $hora"); 


$currentDate = date("Y-m-d");
$currentTime = date("H:i:s");
$currentDate =  date("Y-m-d H:i:s", strtotime($currentDate .$currentTime));

$end = strtotime("$currentDate"); 



$totaltime = ($end - $start)  ; 

$hours = intval($totaltime / 3600);   
$seconds_remain = ($totaltime - ($hours * 3600)); 

$minutes = intval($seconds_remain / 60);   
$seconds = ($seconds_remain - ($minutes * 60));
$statusfichaje= $row["status"];
if ($statusfichaje == Start){echo '<td>Trabajando'.$hours.':'.$minutes.':'.$seconds.' </td>';}else{echo '<td>'. $row["status"] .'</td>';}

Edit

start 2019-12-29 21:27:50 . end 2019-12-31 0:51:50 = 47:51:16

As you can see it calculates badly.

A simple example like this would do the job :

$mydatetime = new DateTime();
$datefromdb = new DateTime('2018-03-05 10:10:00');
$interval = $mydatetime->diff($datefromdb);
$date_count = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
echo $date_count;

This is your code it should work

$fecha = $row["fecha"];
$data= $row["hora"];
$start = strtotime("$fecha $data"); 


$currentDate = date("Y-m-d");
$currentTime = date("H:i:s");
$currentDate =  date("Y-m-d H:i:s", strtotime($currentDate .$currentTime));

$end = strtotime("$currentDate"); 



$totaltime = ($end - $start)  ; 

$hours = intval($totaltime / 3600);   
$seconds_remain = ($totaltime - ($hours * 3600)); 

$minutes = intval($seconds_remain / 60);   
$seconds = ($seconds_remain - ($minutes * 60));
$statusfichaje= $row["status"];
if ($statusfichaje == $start){echo '<td>Trabajando'.$hours.':'.$minutes.':'.$seconds.' </td>';}else{echo '<td>'. $row["status"] .'</td>';}

problem was in the string.

  $data= $row["hora"];

and I use this

$start = strtotime("$fecha $hora");

And don't take the hours and calculate only for days.

Thank you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM