PHP中两个日期的总和 [英] Sum of two dates in PHP
问题描述
我怎么可以对两个日期求和?
how I can sum two dates?
我有两个这样的日期jh:i:s,我想对它们进行求和
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}";
}
?>
用法:
我所需要的是将两个任务的两个日期相加,例如:
任务1将花费1天10小时20分钟10秒
任务2将花费3天17小时35分钟40秒
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
所以结果将是任务1和任务2之间的总时间
so the result will be the total time between task 1 and two
推荐答案
只需使用strtotime并对时间戳求和,然后使用日期函数再次转换为日期:
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?
这篇关于PHP中两个日期的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!