简体   繁体   English

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

[英]How do you calculate an end time based on start time and duration?

I'm building a event calendar and pass a start time to PHP, in the format of 2009-09-25 15:00:00. 我正在构建一个事件日历并将开始时间传递给PHP,格式为2009-09-25 15:00:00。 A duration gets passed as well, that might be in the format of 60 minutes or 3 hours. 持续时间也会通过,可能是60分钟或3小时的格式。 Converting from hours to minutes isn't the problem. 从小时转换为分钟不是问题。 How do you add a length of time to an established starting point to correctly format the end time? 如何为确定的起点添加一段时间以正确格式化结束时间?

Easy way if you have a sufficiently high version number: 如果您有足够高的版本号,可以轻松实现:

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

Using strtotime() you can convert the current time (2009-09-25 15:00:00) to a timestamp and then add (60 * 60 * 3 = 3hrs) to the timestamp. 使用strtotime(),您可以将当前时间(2009-09-25 15:00:00)转换为时间戳,然后将(60 * 60 * 3 = 3小时)添加到时间戳。 Finally just convert it back to whatever time you want. 最后只需将其转换回您想要的任何时间。

//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);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM