Weird issue with php DateTime...

Jaxel

Well-known member
Assuming 2018, 01...

Code:
        $visitor = \XF::visitor();
        $strTime = new \DateTime('now', new \DateTimeZone($visitor->timezone));
        $strTime->setDate($params->year, $params->month, 1);
        $strTime->setTime(0,0,0);
        
        $endTime = $strTime;
        $endTime->modify('+1 month -1 day');
        
        \XF::dump($strTime->format('r'));
        \XF::dump($endTime->format('r'));

You would think this would output the first of the month, and the last of the month.

Instead its outputting both values as the last of the month. What am I doing wrong?
 
$strTime is an object and objects are passed by reference, not by value. So you need to clone the object.
Code:
        $visitor = \XF::visitor();
        $strTime = new \DateTime('now', new \DateTimeZone($visitor->timezone));
        $strTime->setDate($params->year, $params->month, 1);
        $strTime->setTime(0,0,0);
       
        $endTime = clone $strTime;
        $endTime->modify('+1 month -1 day');
       
        \XF::dump($strTime->format('r'));
        \XF::dump($endTime->format('r'));
 
Last edited:
I believe you can also use the DateTimeImmutable class for a similar effect, but it wasn't introduced until PHP 5.5.
 
Top Bottom