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.
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");
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.
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 ...
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With