How do I deep copy a DateTime object?

0 votes
asked Apr 5, 2010 by billy-oneal
$date1 = $date2 = new DateTime();
$date2->add(new DateInterval('P3Y'));

Now $date1 and $date2 contain the same date -- three years from now. I'd like to create two separate datetimes, one which is parsed from a string and one with three years added to it. Currently I've hacked it up like this:

$date2 =  new DateTime($date1->format(DateTime::ISO8601));

but that seems like a horrendous hack. Is there a "correct" way to deep copy a DateTime object?

4 Answers

0 votes
answered Apr 5, 2010 by amy-b
$date1 = new DateTime();
$date2 = new DateTime();
$date2->add(new DateInterval('P3Y'));

Update:

If you want to copy rather than reference an existing DT object, use clone, not =.

$a = clone $b;

0 votes
answered Apr 28, 2013 by rjmunro

Clone the date with the clone operator:

$date1 = new DateTime();
$date2 = clone $date1;
$date2->add(new DateInterval('P3Y'));

Clones are shallow by default, but deep enough for a DateTime. In your own objects, you can define the __clone() magic method to clone the properties (i.e. child objects) that make sense to be cloned when the parent object changes.

(I'm not sure why the documentation thinks a good example of needing to clone an object is GTK. Who uses GTK in PHP?)

0 votes
answered Apr 10, 2015 by alexander-garden

PHP 5.5.0 introduced DateImmutable. add and modify methods of this class return new objects.

$date1 = new DateTimeImmutable();
$date2 = $date1->add(new DateInterval('P3Y'));
0 votes
answered Sep 15, 2017 by hossein-shahdoost

You should change your DateTime to DateTimeImmutable

// from date time
$date = \DateTimeImmutable::createFromMutable($mutableDate)

then you can call any method on the DateTime without worrying about it change

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...