Search code examples
phpmysqlelapsedtime

elapsed time from database


I am trying to create an elapsed time using date_purchased from a database table called order. I know I am getting the date_purchased as I can

<?php echo zen_datetime_short($order->info['date_purchased']); ?>

and get the date and time formatted as 04/20/2014 11:19:56 I'm not good with php and am just starting to learn this but from what I have researched I have tried the following

<?php
$first  = $order->info['date_purchased'];
$second = new DateTime( 'Y-m-d H:i:s' );
$diff = $first->diff( $second );
?>

Then I do

<?php echo $diff->format( '%H:%I:%S' ); ?>

Unfortunately the page loads up until my echo and then everything that should appear below it doesn't. I preferably would only want to show minutes and seconds on my output.

Thanks for your help. I'm using php 5.3 on my server.


Solution

  •      $dt = date('Y-m-d H:i:s');
         echo $dt."<br>";
    
         $difference = strtotime($dt) - strtotime("20-04-2014 20:14:30");
    
        // getting the difference in minutes
         $difference_in_hours = $difference / (60*60);
    
         echo $difference_in_hours."<br>";
    
        function sECONDS_TO_DHMS($seconds)
          {
    
             $days = floor($seconds/86400);
             $hrs = floor($seconds/3600);
             $mins = intval(($seconds / 60) % 60); 
             $sec = intval($seconds % 60);
    
                if($days>0){
                  //echo $days;exit;
                  $hrs = str_pad($hrs,2,'0',STR_PAD_LEFT);
                  $hours=$hrs-($days*24);
                  $return_days = $days." Days ";
                  $hrs = str_pad($hours,2,'0',STR_PAD_LEFT);
             }else{
              $return_days="";
              $hrs = str_pad($hrs,2,'0',STR_PAD_LEFT);
             }
    
             $mins = str_pad($mins,2,'0',STR_PAD_LEFT);
             $sec = str_pad($sec,2,'0',STR_PAD_LEFT);
    
             return $return_days.$hrs.":".$mins.":".$sec;
          }
          echo sECONDS_TO_DHMS($difference);
    

    replace the second time field with the datetime you are taking from the database.