quicksnack86
quicksnack86

Reputation: 89

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

how to add 6 hours to this string?

$parent = "2011-08-04 15:00:01";

I think the best way is to convert it to timestamp add 21600 seconds and then convert it back to date time.

How to do this?

Thanks in advance.

Upvotes: 1

Views: 8185

Answers (6)

hatef
hatef

Reputation: 6219

For PHP > 5.3 you can use the DateInterval class on a DateTime object, which I think is the easiest way to deal with the complexity of time calculations. So in your case you could do something like this:

$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

Upvotes: 0

RiaD
RiaD

Reputation: 47650

Seems like timestamp/datetime value from SQL. You can use for it

SELECT datefield + INTERVAL 6 HOUR

Upvotes: 0

Jonathan M
Jonathan M

Reputation: 17451

date('Y-m-d H:i:s', strtotime($parent) + 21600);

Upvotes: 0

yokoloko
yokoloko

Reputation: 2860

You're maybe looking for the http://www.php.net/manual/en/function.strtotime.php function

$timestamp = strtotime("2011-08-04 15:00:01");
$timestamp += 6 * 3600;
echo date('Y-m-d H:i:s', $timestamp);

Upvotes: 5

Sjoerd
Sjoerd

Reputation: 75649

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

Upvotes: 1

Chris Muench
Chris Muench

Reputation: 18338

$sixhours_from_parent = strtotime($parent) + 21600;
$sixhours_date = date('Y-m-d H:i:s', $sixhours_from_parent);

Upvotes: 1

Related Questions