Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of two dates in PHP

Tags:

date

php

sum

how I can sum two dates?

I have two date in this format j h:i:s and I will like to sum them

I found this script but no reference about days and I'm new to this, here is the script, maybe somebody can make the necessary changes.

<?php

/**
 * @author Masino Sinaga, http://www.openscriptsolution.com
 * @copyright October 13, 2009
 */

echo sum_the_time('01:45:22', '17:27:03');  // this will give you a result: 19:12:25

function sum_the_time($time1, $time2) {
  $times = array($time1, $time2);
  $seconds = 0;
  foreach ($times as $time)
  {
    list($hour,$minute,$second) = explode(':', $time);
    $seconds += $hour*3600;
    $seconds += $minute*60;
    $seconds += $second;
  }
  $hours = floor($seconds/3600);
  $seconds -= $hours*3600;
  $minutes  = floor($seconds/60);
  $seconds -= $minutes*60;
  return "{$hours}:{$minutes}:{$seconds}";
}

?>

Usage:

All that I need is to sum two dates from two task like: Task 1 will take 1 day 10 hour 20 mins 10 sec Task 2 will take 3 days 17 hours 35 mins 40 sec

so the result will be the total time between task 1 and two

like image 292
Daniel Avatar asked Oct 31 '25 04:10

Daniel


1 Answers

just convert the dates using strtotime and sum the timestamps, than convert to the date again using date function:

$tmstamp = strtotime($date1) + strtotime($date2);
echo date("Y m d", $tmstamp) ;

but why would you add two dates in the first place?

like image 197
Headshota Avatar answered Nov 01 '25 18:11

Headshota



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!