I have a question regarding the proper way to modify a php DateTime object. Currently, I’m doing something like:
$origEvent = new DateTime(...);
$newEvent = new DateTime(...);
$someOtherEvent = new DateTime(...);
//get the time difference between the orignal event and the edited event
$diff = $origEvent->diff($newEvent);
$someOtherEvent->add($diff);
Using the DateTime::add() method seems to work whether we are adding or subtracting time from $someOtherEvent. Is this the correct way to do this? I know there is DateTime::sub() used for subtracting time, but it seems that as long as the DateInterval (produced by the $origEvent->diff()) has the inverted flag, the DateTime::add() knows to actually subtract time. Is this correct? Should I be using something like DateTime::modify?
Actually, DateTime::diff() returns the difference between two DateTime objects in a relative manner. Thus :
So :
For reasons of clarity of the code you can set the second parameter of DateTime::diff() to true in order to get an absolute difference every time and then choose the best function between DateTime::add() and DateTime::sub() knowing that you have an absolute difference.
Some words about the choice between DateTime::modify() and DateTime::add(), DateTime:sub() :