0

I want to add two time() and get the result. for example i get time1 as 1395897426 and time2 as 1395897487 now i want to add those two time in a variable time3 and convert it to hours and minutes

    <?php 
    $time1 =time();
    $time2 = time();
    $time3 = $time1+$time2;
    echo $time3;
    ?>

actually am using a function to find time difference. function time_diff($start,$end)

{
       $time1 = date('H:i',$start);
       $time2 = date('H:i',$end);
       list($hours, $minutes) = explode(':', $time1);
       $startTimestamp = mktime($hours, $minutes);

       list($hours, $minutes) = explode(':', $time2);
       $endTimestamp = mktime($hours, $minutes);

       $seconds = $endTimestamp - $startTimestamp;
       $minutes = ($seconds / 60) % 60;
       $hours = round($seconds / (60 * 60));
       echo "<b>$hours</b> hours and <b>$minutes</b> minutes";
}
user3239311
  • 187
  • 1
  • 4
  • 15
  • 2
    The numbers represent both date and time. What would the sum of 'May 1 2011 08:00:00' and 'June 4 2014 17:20:00' sensibly be? – Joachim Isaksson Mar 27 '14 at 05:45
  • 2
    Are you sure you want to do that ? Can you post an example with two dates and output you expect ? – Rikesh Mar 27 '14 at 05:45
  • actually i have two total work hours as some minutes and hours (e.x: 4hours 5minutes, 3hours 20minutes) now i want to add the sum of those two hours. @Rikesh – user3239311 Mar 27 '14 at 05:48
  • @JoachimIsaksson am sorry about my question. what i want is, to sum all total hours and minutes in a column (for example: 4hours 30minutes, 5hours 30minutes, 2hours 15minutes) it has to be summed up and the reuslt should be 12hours 15minutes – user3239311 Mar 27 '14 at 05:53
  • @Rikesh You're probably right. I think I probably misunderstood the question seeing as I didn't see the OP's last comment before I posted my answer. – Mike Mar 27 '14 at 06:08
  • @user3239311 How is the data stored? As text, like "4hours 30minutes"? – Mike Mar 27 '14 at 06:10
  • @Mike No actually its echoed as echo "$hours hours and $minutes minutes"; you can see the time_diff() in my post – user3239311 Mar 27 '14 at 06:13
  • @user3239311 That's not what I meant. How is it actually *stored*, as in, when it's in your database. Is it a Unix timestamp, MySQL timestamp, VARCHAR, etc? And if it's VARCHAR how is it formatted? – Mike Mar 27 '14 at 18:13

1 Answers1

1

Instead of fiddling around with it, let DateTime do all the work for you.

$time1 = new DateTime;
$time2 = new DateTime("2014-03-25 06:52:21");

$interval = $time2->diff($time1);

// Get number of days and multiply by 24 hours
$elapsed['h'] = $interval->format('%a') * 24;
// Then add in hours
$elapsed['h'] += $interval->format('%h');

// Minutes
$elapsed['m'] = $interval->format('%i');

echo $elapsed['h'] . ' hours and ' . $elapsed['m'] . ' minutes';
// produces 41 hours and 3 minutes
Mike
  • 23,542
  • 14
  • 76
  • 87