How do I deep copy a DateTime object?

datetime copy python
php deep copy array
shallow copy and deep copy in php
datetime copy c#
php clone variable
datetime clone php
php datetime::modify
php copy object property
$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?

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


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

$a = clone $b;

How to copy a DateTime object in PHP ?, When an object is cloned, PHP will perform a shallow copy of all of the object's properties. echo (clone $dateTime)->format('Y'); A (or more indirect loops than that), then you'll be glad that clone does NOT automatically make a deep copy! 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.

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?)

Object Cloning - Manual, Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable  It's probably possible to use reflection to recursively walk through the object graph to do a deep copy. WCF uses this technique to serialize an object, including all of its children. The trick is to annotate all of the child objects with an attribute that makes it discoverable. You might lose some performance benefits, however. Update

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

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

8.17. copy — Shallow and deep copy operations, $date2 = new DateTime($date1->format(DateTime::ISO8601));. but that seems like a horrendous hack. Is there a “correct” way to deep copy a  If the properties you want to copy are DateTime the deep copy/shallow copy thing is irrelevance DateTime is a value type a copy of the value because there is no reference to copy.

$date1 = new DateTime();
$date2 = (clone $date1)->modify('+3 years');

(Shallow copy is enaugh - Deep copy-ing DateTime makes (currently) no sense)

Simple as that :)
Explanation "php create datetime object from another datetime":
  1. The clone keyword makes regular shallow copy - enaugh for this case (why => see below)
  2. Wraping it with () evaluates the expression returning the newly created object by clone
  3. ->modify() is therefore called on and modifies the new object
  4. DateTime::modify(...) docs:

    Returns the DateTime object for method chaining or FALSE on failure.

  5. $date2 now contains the newly created & modified clone/copy, while $date1 remains unchanged

Why you don't need to deep copy here:

Deep copy/clone is only necessary, when you need to copy targets of properties that are references, but this:

class TestDateTime extends DateTime{
  public function test(){
   //*this* way also outputs private variables if any...
   var_dump( get_object_vars($this) );    
$test = (new TestDateTime())->test();


array(3) {
  string(26) "2019-08-21 11:38:48.760390"
  string(3) "UTC"

so there are no references, just simple types => no need to deep copy.

How do I deep copy a DateTime object?, The deep copy creates independent copy of original object and all its nested objects. Example 5: Copying a list using deepcopy().;; IPython  Deep Copy: It is a process of creating a new object and then copying the fields of the current object to the newly created object to make a complete copy of the internal reference types. If the specified field is a value type, then a bit-by-bit copy of the field will be performed.

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

Python Shallow Copy and Deep Copy (With Examples), Not all objects can be copied, but most can. import copy newobj = copy.copy(​oldobj) # shallow copy newobj = copy.deepcopy(oldobj) # deep (  Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy. An object copy is created by using the clone keyword (which calls the object's __clone() method if possible).

How do I copy an object in Python?, Which method is used to tweak an object's cloning behavior? A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

What is the difference between a deep copy and a shallow copy , DatetimeIndex. copy (name=None, deep=False, dtype=None, **kwargs)[source]¶​. Make a copy of this object. Name and dtype sets those attributes on the new  A deep copy of an Object results in copies and the original Object not referencing the same reference type member Object in memory. This article is a follow up article on: C# How to: Deep copy objects using Binary Serialization .

How to create a copy of an object in PHP?, as is done in the constructor (which takes a DateTime object, shown in bold), implement either a shallow copy (calling MemberwiseClone) or a deep copy  The deep copy approach in Java will copy the entire object tree and thus make this copy independent from the original object.In this article, we will focus on a deep copy of an object in Java.Deep cloning is closely related to Java serialization. 1. Deep Copy. Deep copy technique

  • I used a new DateTime in the example to demonstrate the point, but for now assume DateTime is returned from some opaque API that I can't just call over again. For example, I have a function that handles orders that returns a DateTime which is when the customer can next place an order. Calling the function to create a copy produces side effects I don't want.
  • I haven't tested it actually, but it is mentioned at that this is only aviable for PHP 5.3 and greater.
  • @hugo: Yes, the DateTime class requires PHP 5.3.
  • Just when I thought I had a grasp over PHP I learn about a new operator.
  • Had to do this to copy an existing Carbon object to another variable. This worked.
  • Thank you for the answer, but how do you know it's deep enough for DateTime? Which attributes remain references and which are copied by value? For example, I can change the time and timezone and it won't affect the clone?
  • @David: I know it's deep enough for DateTime because I tried it, and it worked for me. I didn't try changing the timezone or any other things, just the basic time and date.
  • Using Xdebug, var_dump($date1) reports that it contains 'date' => string, 'timezone_type' => int & 'timezone' => string. Since it doesn't appear to contain any arrays or objects, just basic scalars, a shallow clone should be fine.
  • Note that unfortunately you can't just swap a DateTime with a DateTimeImmutable. There's at least IntlDateFormatter::formatObject that doesn't like immutables (returns false instead of the formatted string).
  • oh! I somehow never knew this existed, though I've long dreamt of it. and all the way back in 5.5...
  • Like some noob I just encountered an object oriented pitfall by modifying my DateTime object in a for loop :D This nicely solved it...
  • @user276648 This bug is now fixed in php 7.1.5
  • This is really an answer to a different question.
  • @BillyONeal I might have not explained fully how, But this is a solution to this problem as the source of this problem is how calling the method add on date2 changes the value of date1 and there is no way to copy the value of DateTime variable unless you have an DateTimeImmutable