Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php string in a 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 the entry within PHP, then save it back to string in the same format

I believe this involves converting the string to a date object. But I'm not sure how smart the date object is and if I need to tell it formatting parameters or if it is supposed to just take the 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 getting back empty values from this method or a similar one I tried

How would you solve this issue?

Thanks, your insight is appreciated

like image 339
CQM Avatar asked Mar 05 '13 16:03

CQM


People also ask

How can increase day in date in PHP?

You can use strtotime. $your_date = strtotime("1 day", strtotime("2016-08-24")); $new_date = date("Y-m-d", $your_date);

What does Strtotime mean in PHP?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.


3 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("Y-m-d H:i:sO");

See it in action

Here's an example using a DateInterval object:

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

See it in action

like image 90
John Conde Avatar answered Nov 04 '22 17:11

John Conde


Change this line

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

with

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

this will add 12 hours to your date

Look at the DateInterval constructor page to know how to build the DateInterval string

like image 43
Davide Berra Avatar answered Nov 04 '22 18:11

Davide Berra


Use this to add hours,

$date1= "2014-07-03 11:00:00";
$new_date= date("Y-m-d H:i:s", strtotime($date1 . " +3 hours"));
echo $new_date;
like image 22
Gayan Fernando Avatar answered Nov 04 '22 18:11

Gayan Fernando