Add hours to UTC dateTime

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

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?

回答1:

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:



回答2:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!