質問

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 :

  • If date1 is lower than date2 then date1->diff(date2) will result in a negative interval
  • If date2 is lower than date1 then date1->diff(date2) will result in a positive interval

So :

  • The use of DateTime::add() with a negative interval is equivalent to the use of DateTime::sub() with the absolute value of this same interval
  • The use of DateTime::sub() with a negative interval is equivalent to the use of DateTime::add() with the absolute value of this same interval

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() :

  • As long as you are using DateTime::diff() you are assuming that your PHP version is greater than or equal to 5.3.0, and you can use all new functions available in this PHP version; that is to say DateTime::add() and DateTime::sub()
  • The use of DateTime::modify() is justified when your PHP version is greater than or equal to 5.2.0. (In this version DateTime::add() and DateTime::sub() are not yet available)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top