php string in a date format, add 12 hours
Asked Answered
T

4

6

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

Tortoni answered 5/3, 2013 at 16:18 Comment(0)
P
21

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

Prosecute answered 5/3, 2013 at 16:20 Comment(1)
And if you need the offset, it's $date->format("Y-m-d H:i:sO");Glanville
P
2

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

Premundane answered 5/3, 2013 at 16:28 Comment(1)
okay, I saw that syntax on the dateAdd reference site php.net/manual/en/datetime.add.php but I couldn't find the reference telling me what P12H was and other kinds of intervals, if it was there it wasn't very intuitive. Come to think of it, maybe it is on the dateinterval pageTortoni
F
2

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;
Flapper answered 12/7, 2014 at 2:20 Comment(0)
D
1

If you have dynamic interval, this way will avoid errors of wrong format 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("Y-m-d H:i:sO");
Discalced answered 21/2, 2017 at 9:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.