Sethen
Sethen

Reputation: 11348

Add hours to UTC dateTime

I am sure the answer is right in front of me, but I have a UTC dateTime that looks like this:

2014-01-02 04:02:58

All I want to do is add some hours to that.

How can I achieve this in PHP? Further, how would I add days to it if I wanted to?

Upvotes: 0

Views: 3306

Answers (2)

John Conde
John Conde

Reputation: 219804

Use DateTime(). Unlike date()/strtotime() it is timezone and daylight savings time friendly.

// PHP 5.2+
$dt = new DateTime('2014-01-02 04:02:58');
$dt->modify('+2 hours');
echo $dt->format('Y-m-d H:i:s');
$dt->modify('+2 days');
echo $dt->format('Y-m-d H:i:s');

See it in action

Or

// PHP 5.3+
$dt = new DateTime('2014-01-02 04:02:58');
$dt->add(new DateInterval('PT2H'));
echo $dt->format('Y-m-d H:i:s');
$dt->add(new DateInterval('P2D'));
echo $dt->format('Y-m-d H:i:s');

See it in action

Or

// PHP 5.4+
echo (new DateTime('2014-01-02 04:02:58'))->add(new DateInterval('PT2H'))->format('Y-m-d H:i:s');

See it in action

Reference:

Upvotes: 3

Mahmood Rehman
Mahmood Rehman

Reputation: 4331

You can use strtotime() try like this :

echo $new_time = date("Y-m-d H:i:s", strtotime( "2014-01-02 04:02:58".'+3 hours'));

Upvotes: 2

Related Questions