Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding months to DateTime with DateInterval changes original date to match new date

Tags:

php

datetime

I have this pretty simple code:

$start_date = new DateTime($post['start_date']);
$end_date = $start_date->add(new DateInterval('P6M'));
echo $start_date->getTimestamp(); // 1351836000
echo $end_date->getTimestamp(); // 1351836000

Of course, both end up as the same timestamp because adding the date interval affects the original $start_date. So how do I go about this so I can keep the original $start_date yet add 6 months to it in another variable?

I tried this with no luck:

$start_date = new DateTime($post['start_date']);
$start_date_actual = $start_date;
$end_date = $start_date_actual->add(new DateInterval('P6M'))->getTimestamp();
like image 294
dallen Avatar asked May 02 '12 18:05

dallen


People also ask

How can increase month in date in PHP?

Sample Solution: PHP Code: <? php $dt = strtotime("2012-12-21"); echo date("Y-m-d", strtotime("+1 month", $dt)).

How do I use DateInterval?

A common way to create a DateInterval object is by calculating the difference between two date/time objects through DateTimeInterface::diff(). Since there is no well defined way to compare date intervals, DateInterval instances are incomparable.

What is date interval?

The span of time between a specific start date and end date.

What is the use of date () function in PHP?

The date() function formats a local date and time, and returns the formatted date string.


1 Answers

Variables hold references to objects, not the objects themselves. So assignment just gets you more variables pointing to the same object, not multiple copies of the object.

If you want a copy, use the clone keyword:

$end_date = clone $start_date;
$end_date->add(new DateInterval('P6M'));
like image 162
Mark Reed Avatar answered Nov 03 '22 13:11

Mark Reed