0

It's finally time to make the jump! The below code used to work on PHP 5.6

I move to 7.1, and it's failing. What am I doing wrong?

$expectedToday = new DateTime();
$expectedToday->sub(new DateInterval('PT5H'));
$this->assertEquals($expectedToday, functionThatReturnsDateTimeSuccessfully()));

I get

Failed asserting that two DateTime objects are equal.
--- Expected
+++ Actual
@@ @@
 2019-03-15T08:35:21+0000

So functionThatReturnsDateTimeSuccessfully is plainly working.

However, when I comment out the second line

$expectedToday = new DateTime();
// $expectedToday->sub(new DateInterval('PT5H'));
$this->assertEquals($expectedToday, functionThatReturnsDateTimeSuccessfully()));

I get

Failed asserting that two DateTime objects are equal.
--- Expected
+++ Actual
@@ @@
-2019-03-15T13:38:31+0000
+2019-03-15T08:38:31+0000

So my question is - what am I doing wrong? Why does sub appear to empty the contents of the whole DateTime object? If this function's borked why don't they deprecate?

--- UPDATE ---

The same issue does not occur with add. This is just with sub.

JohnFF
  • 723
  • 5
  • 20
  • What does a simple `var_dump` of `$expectedToday` give? Note that both assertions are *failing*, and that the first assertion gives no clear `---` expected or `+++` actual output, so it's hard to clearly pin the failure on `sub`… – deceze Mar 15 '19 at 15:57
  • The first gives a +++, just not a --- . That's the odd thing. It's like Sub is NULLing out the internal vars, or something. – JohnFF Mar 15 '19 at 16:11
  • Can you show 'functionThatReturnsDateTimeSuccessfully' too? – Mariyo Mar 15 '19 at 16:17
  • Incredibly strange. `sub` looks consistent [here](https://3v4l.org/MgMCr) – Darragh Enright Mar 15 '19 at 16:22
  • Off-topic, and I assume it's just a typo—but there's an extra closing parenthesis in your `assertEquals()` call – Darragh Enright Mar 15 '19 at 16:23
  • Updating from one dead version of PHP (5.6) to another dead version of PHP (7.1) does not really make sense. – Sebastian Bergmann Mar 16 '19 at 07:26

1 Answers1

1

You can check reference link Why can't I access DateTime->date in PHP's DateTime class? Is it a bug?

So to resolve this issue, you should get date with setting its format as below:

$expectedToday = new DateTime();
$expectedToday->sub(new DateInterval('PT5H'));
$this->assertEquals($expectedToday->format('Y-m-d H:i:s'), "2019-03-10 15:15:15");

Hope it helps you.

Rohit Mittal
  • 2,064
  • 2
  • 8
  • 18