问题
I'm building a event calendar and pass a start time to PHP, in the format of 2009-09-25 15:00:00. A duration gets passed as well, that might be in the format of 60 minutes or 3 hours. 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?
回答1:
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. 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);
回答2:
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";
回答3:
As an addendum to @Xeoncross's good strtotime
answer, strtotime()
supports formats like "2009-09-25 +3 hours", "September 25 +6 days", "next Monday", "last Friday", "-15 minutes", etc.
来源:https://stackoverflow.com/questions/1318974/how-do-you-calculate-an-end-time-based-on-start-time-and-duration