tags:

views:

204

answers:

1
$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?

+2  A: 
$date1 = new DateTime();
$date2 = new DateTime();
$date2->add(new DateInterval('P3Y'));

This seems pretty damn obvious, so if I'm just not understanding, let me know.

Update:

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

$a = clone $b;

Coronatus
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.
Billy ONeal