Php string in date format, add 12 hours

I have this string object in my php array

"2013-03-05 00: 00: 00 + 00"

I would like to add 12 hours to a post in PHP and then save it back to a string in the same format

I believe this is due to converting the string to a date object. But I'm not sure how smart the date object is, and if I need to specify formatting options or is it supposed to just take a string

 $date = new DateTime("2013-03-05 00:00:00+00"); $date->add("+12 hours"); //then convert back to string or just assign it to a variable within the array node 

I was returning empty values ​​from this method or similar ones that I tried

How would you solve this problem?

Thank you, your understanding is appreciated.

+6
source share
4 answers

Change add() to modify() . add() expects a DateInterval object.

 <?php $date = new DateTime("2013-03-05 00:00:00+00"); $date->modify("+12 hours"); echo $date->format("Ymd H:i:sO"); 

Look in action

Here is an example using the DateInterval object:

 <?php $date = new DateTime("2013-03-05 00:00:00+00"); $date->add(new DateInterval('PT12H')); echo $date->format("Ymd H:i:sO"); 

Look in action

+20
source

Change this line

 $date->add("+12 hours"); 

with

 $date->add(new DateInterval("PT12H")); 

it will add 12 hours to your date

Take a look at the DateInterval constructor to learn how to build a DateInterval string DateInterval

+2
source

Use this to add a watch,

 $date1= "2014-07-03 11:00:00"; $new_date= date("Ymd H:i:s", strtotime($date1 . " +3 hours")); echo $new_date; 
+1
source

If you have a dynamic interval, this method will help you avoid the wrong format errors for $ dateDiff:

 $dateDiff = "12 hours"; $interval = DateInterval::createFromDateString($dateDiff); $date = new DateTime("2013-03-05 00:00:00+00"); $date->add($interval); echo $date->format("Ymd H:i:sO"); 
0
source

All Articles