Chuck Le Butt
Chuck Le Butt

Reputation: 48758

Add days to DateTime in PHP -- without modifying original

How can I add a number of days to a DateTime object without modifying the original. Every question on StackOverflow appears to be about date and not DateTime, and the ones that do mention DateTime talk about modifying the original.

Eg.

$date = new DateTime('2014-12-31');
$date->modify('+1 day');

But how can you calculate a date several days in advance without modifying the original, so you can write something like:

if($dateTimeNow > ($startDate + $daysOpen days) {
   //
}

I could always just create another DateTime object, but I'd rather do it the above way.

Upvotes: 12

Views: 5680

Answers (2)

Vivek Singh
Vivek Singh

Reputation: 2447

you can take the original variable in a separate variable and add no. of days in other variable so you have both(original and updated)value in different variable.

    $startDate = new DateTime('2014-12-31');    
    $endDate = clone $startDate;
    $endDate->modify('+'.$days.'days');
    echo $endDate->format('Y-m-d H:i:s');

You can always use clone, too:

$datetime = clone $datetime_original;

Upvotes: 6

maztch
maztch

Reputation: 1697

Use DateTimeImmutable, it's the same as DateTime except it never modifies itself but returns a new object instead.

http://php.net/manual/en/class.datetimeimmutable.php

Upvotes: 16

Related Questions