Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify original DateTime object without change its value?

Tags:

php

datetime

I'm trying to get the current date/time using OOP way as follow:

$now = new \DateTime(); // 2015-05-24 11:21:36 -> this works fine

and also I'm adding 1 week to the same object $now so I did this:

$expireTime = $now->modify('+1 week'); // 2015-05-31 11:21:36 -> this also works fine

In the same method if I do this:

echo $now; 
// Output: 2015-05-31 11:28:59
// Got wrong value, should be original date without modification

echo $expireTime;
// Output: 2015-05-31 11:28:59 
// Got the right value since I have added 1 week

Why? How do I add a week without modify the original object?

EDIT: I have found the solution by cloning the original object and modifying the cloned one but I want to know if this behavior is right and why

like image 762
ReynierPM Avatar asked May 24 '15 16:05

ReynierPM


1 Answers

You are probably looking for the DateTimeImmutable class, which is the same, but it doesn't change the original value. As from the manual:

This class behaves the same as DateTime except it never modifies itself but returns a new object instead.

like image 177
Rizier123 Avatar answered Nov 16 '22 11:11

Rizier123