如何将日期时间转换为时间戳,在PHP中添加6小时并将其转换回日期时间


How to convert date time to timestamp, add 6 hours and convert it back to date time in PHP?

如何添加6小时到这个字符串?

父美元="2011-08-04 15:00:01";

我认为最好的方法是将其转换为时间戳添加21600秒,然后将其转换回日期时间。

如何做到这一点?

您可能正在寻找http://www.php.net/manual/en/function.strtotime.php函数

$timestamp = strtotime("2011-08-04 15:00:01");
$timestamp += 6 * 3600;
echo date('Y-m-d H:i:s', $timestamp);
$sixhours_from_parent = strtotime($parent) + 21600;
$sixhours_date = date('Y-m-d H:i:s', $sixhours_from_parent);
<?php
$parent = "2011-08-04 15:00:01";
$parentTime = strtotime($parent);
$later = strtotime("+6 hours", $parentTime);
echo date('Y-m-d H:i:s', $later);
?>
date('Y-m-d H:i:s', strtotime($parent) + 21600);

看起来像SQL中的timestamp/datetime值。你可以用

SELECT datefield + INTERVAL 6 HOUR

对于PHP> 5.3,您可以在DateTime对象上使用DateInterval类,我认为这是处理时间计算复杂性的最简单方法。在你的例子中,你可以这样做:

$time = new 'DateTime("2011-08-04 15:00:01");
$time->add(new 'DateInterval('PT6H')); //add six hours
echo $time->format('Y-m-d H:i:s');

Ref