how to add 48 hours to a timestamp

user3843997 picture user3843997 · Oct 21, 2014 · Viewed 9k times · Source

I am using this code to minus 48 hours from a timestamp

echo date($result2["datetime"], strtotime("-48 hours"));

This works fine, i want to add 48 hours, i have tried:

echo date($result2["datetime"], strtotime("+48 hours"));

I have echoed $result2["datetime"]; which shows a timestamp in the format Y-m-d H:i:s

and when i use:

echo date('Y-m-d H:i:s', strtotime("+48 hours"));

that adds the 48 hours on fine too

When i use

echo date($result2["datetime"], strtotime("+48 hours"));

Its just echoing the same timestamp thats returned from $result2["datetime"]; and not +48 hours

Answer

John Conde picture John Conde · Oct 21, 2014

The first parameter for date() is the format you want the date output in. The second parameter is the value you wish to format. There you will use strtotime() to add your 48 hours.

echo date('Y-m-d H:i:s', strtotime($result2["datetime"] . " +48 hours"));

Demo

or:

echo date('Y-m-d H:i:s', strtotime("+48 hours", strtotime($result2["datetime"])));

Demo

This is kind of ugly, though. I recommend using DateTime() instead:

echo (new DateTime($result2["datetime"]))->modify('+48 hours')->format('Y-m-d H:i:s');

Demo