开发者

Sum of two dates in PHP

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($se开发者_如何转开发conds/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


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?


BAsically what they do, is convert hours and minutes into seconds and add those. Then they convert back to hours/minutes.

You simply have to convert days to seconds too:

$seconds += $days * 3600 * 24 

and then convert back:

$days = floor($seconds/(3600*24));
$seconds -= $days*3600*24
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜