phpdatetimedateinterval

DateInterval doesnt add a date and no errors?


I'm trying to split a holiday in two, given a date in the middle.

$splitdate = new DateTime($_POST['date']);

// Split date = 2020-08-04
$holiday1end = $holiday2start = $splitdate;

$holiday1end->sub(new DateInterval('P1D'));
$holiday2start->add(new DateInterval('P1D'));

echobr("Holiday 1: ".$holiday1end->format("Y-m-d"));
echobr("Then " . $splitdate->format("Y-m-d"));
echobr("Holiday 1: " . $holiday2start->format("Y-m-d");

This is the output I get:

Holiday 1: 2020-08-04
Then 2020-08-04
Holiday 1: 2020-08-04

It doesnt make sense, originally I had the DateInterval as 'P1D' but that didnt work so I tried removing two days, I'm still not getting any changes, or errors either. What am I doing wrong here?

Edit for Clarity: $holiday1end should be one day less than $splitdate, $holiday2start should be one day more than $splitdate, but neither of them are changing.


Solution

  • It seems that when you do like this,

    $splitdate = new DateTime('2010-12-31');
    $holiday1end = $holiday2start = $splitdate;
    

    The instance of object in $splitdate is passed as reference to other variables. And as you are subtracting and adding same number of days, so it seems that the code is not working. However its working properly but due to shared / referenced instance of same object, all effect goes to same object.

    However if you do something like bellow, You'll notice that 1 day is added to date (basically 2 days are subtracted and then 3 days are added).

    $date = '2010-12-31';
    
    $splitdate = new DateTime($date);
    $holiday1end = $holiday2start = $splitdate;
    
    $holiday1end->sub(new DateInterval('P2D'));
    $holiday2start->add(new DateInterval('P3D'));
    
    echo "Holiday 1: ".$holiday1end->format("Y-m-d")."\n";
    echo "Then " . $splitdate->format("Y-m-d")."\n";
    echo "Holiday 2: " . $holiday2start->format("Y-m-d")."\n";
    

    If you separate the DateTime object instances, you'll get your desired results.

    $date = '2010-12-31';
    
    $splitdate = new DateTime($date);
    $holiday1end = new DateTime($date);
    $holiday2start = new DateTime($date);
    
    $holiday1end->sub(new DateInterval('P2D'));
    $holiday2start->add(new DateInterval('P2D'));
    
    echo "Holiday 1: ".$holiday1end->format("Y-m-d")."\n";
    echo "Then " . $splitdate->format("Y-m-d")."\n";
    echo "Holiday 1: " . $holiday2start->format("Y-m-d")."\n";
    

    Working Example of above code

    Example with 1 Day difference