如何根据开始时间和持续时间计算结束时间?

时间:2009-08-23 16:40:40

标签: php datetime time duration

我正在构建一个活动日历并将开始时间传递给PHP,格式为2009-09-25 15:00:00。持续时间也会通过,可能是60分钟或3小时的格式。从小时转换为分钟不是问题。如何为确定的起点添加一段时间以正确格式化结束时间?

3 个答案:

答案 0 :(得分:9)

如果您拥有足够高的版本号,则很容易:

$when = new DateTime($start_time);
$when->modify('+' . $duration);
echo 'End time: ' . $when->format('Y-m-d h:i:s') . "\n";

答案 1 :(得分:7)

使用strtotime(),您可以将当前时间(2009-09-25 15:00:00)转换为时间戳,然后将(60 * 60 * 3 = 3小时)添加到时间戳。最后只需将其转换回您想要的任何时间。

//Start date
$date = '2009-09-25 15:00:00';
//plus time
$plus = 60 * 60 * 3;
//Add them
$time = strtotime($date) + $plus;
//Print out new time in whatever format you want
print date("F j, Y, g:i a", $time);

答案 2 :(得分:0)

作为@ Xeoncross的良好strtotime答案的附录,strtotime()支持“2009-09-25 +3小时”,“9月25日+6天”,“下周一”等格式,上周五“,” - 15分钟“等等。