0

I'm getting incorrect results when adding an interval in a DateTime input string.

Some strings work, some don't. Obviously adding zero shouldn't put the result 5 days in the future and truncate the time. Yikes.

$dtTestStr='2018-09-05 10:25:00-04 + 0 year 0 mon 0 day 00:00:00';
$myFubar=new DateTime($dtTestStr);
echo $dtTestStr. ' is now '.$myFubar->format('Y-m-d H:i:s');

// '2018-09-05 10:25:00-04 + 0 year 0 mon 0 day 00:00:00 is now 2018-09-10 00:00:00'
111
  • 1,788
  • 1
  • 23
  • 38

2 Answers2

1

First of all, you need to use 'month' or 'months' instead of 'mon' and once you eliminate that problem, you have another error. It doesn't know what to do with those zeros. I also removed an extra ) at the end of your echo statement.

You want it to look like this:

$dtTestStr='2018-09-05 10:25:00-04 + 0 year 0 months 0 day 0 hour 0 minute 0 seconds';
$myFubar=new DateTime($dtTestStr);
echo $dtTestStr . ' is now ' . $myFubar->format('Y-m-d H:i:s');

Here's a sandbox link: Sandbox

Difster
  • 3,264
  • 2
  • 22
  • 32
1

The DateTime class thinks that you are asking for the Monday (mon) that follows September 5th, 2018. The following monday is the 10th.

Spelling out month or months will fix your typo.

To be clear, you don't need to assign all those zeroed intervals.

Here's some informative reading regarding several different ways to modify your time data.

Adding minutes to date time in PHP

mickmackusa
  • 43,625
  • 12
  • 83
  • 136