修改 php DateTime 对象


modifying a php DateTime object

我有一个关于修改php DateTime对象的正确方法的问题。 目前,我正在做这样的事情:

$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);

使用 DateTime::add() 方法似乎无论我们从$someOtherEvent中添加或减去时间都有效。 这是正确的方法吗? 我知道有 DateTime::sub() 用于减去时间,但似乎只要 DateInterval(由 $origEvent->diff() 生成)具有倒置标志,DateTime::add() 就知道实际减去时间。 这是对的吗? 我应该使用类似DateTime::modify的东西吗?

实际上,DateTime::d iff() 以相对方式返回两个 DateTime 对象之间的差异。因此:

    如果 date1
  • 小于 date2,则 date1->diff(date2) 将导致区间
  • 如果 date2 小于 date1,则 date1->diff(date2) 将导致区间

所以:

  • 使用负间隔的 DateTime::add() 等效于使用具有相同间隔的绝对值的 DateTime::sub()
  • 使用具有负间隔的 DateTime::sub() 等效于使用具有相同间隔的绝对值的 DateTime::add()

出于代码清晰的原因,您可以将 DateTime::d iff() 的第二个参数设置为 true,以便每次都获得绝对差异,然后在 DateTime::add() 和 DateTime::sub() 之间选择最佳函数,知道您有绝对差异。

关于在DateTime::modify()和DateTime:

:add(),DateTime:sub()之间进行选择的一些话:

  • 只要你使用的是 DateTime::d iff(),你就假设你的 PHP 版本大于或等于 5.3.0,并且你可以使用这个 PHP 版本中可用的所有新函数;也就是说,DateTime::add() 和 DateTime::sub()
  • 当您的 PHP 版本大于或等于 5.2.0 时,使用 DateTime::modify() 是合理的。(在此版本中,DateTime::add() 和 DateTime::sub() 尚不可用)