Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add days to DateTime in PHP -- without modifying original

Tags:

php

datetime

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.

like image 750
Chuck Le Butt Avatar asked Apr 23 '15 11:04

Chuck Le Butt


People also ask

How can add days in date in PHP?

PHP date_add() Function $date=date_create("2013-03-15"); date_add($date,date_interval_create_from_date_string("40 days")); echo date_format($date,"Y-m-d");

How do you add one day to a date?

To add 1 day to a date: Use the getDate() method to get the day of the month for the given date. Use the setDate() method to set the day of the month to the next day. The setDate method will add 1 day to the Date object.

How can I get tomorrow date in PHP?

php // The event date $eventdate = strtotime(get_field('date_time')); // Today's date $today = strtotime('now'); // Tomorrow's date $tomorrow = strtotime('tomorrow'); // If event date is equal to today's date, show TODAY if (date('m-d-Y', $today) == date('m-d-Y', $eventdate)) { echo 'Today'; } // If event date is equal ...


2 Answers

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

like image 105
maztch Avatar answered Oct 12 '22 23:10

maztch


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;
like image 38
Vivek Singh Avatar answered Oct 12 '22 23:10

Vivek Singh