【问题标题】:php DateTime diff - include both dates in range?php DateTime diff - 包括范围内的两个日期?
【发布时间】:2016-07-09 13:33:31
【问题描述】:

我一直在使用 DateTime Diff(在 php 中)来获取日期对的各种设置 - 要显示的两个格式化日期,从日期到现在的差异(例如“开始日期是 3 个月 2 天前”),以及两个日期之间的长度(“长度为 2 个月 3 天”)。

问题是 DateTime Diff 忽略了其中一天,所以如果开始是昨天,结束是明天,它给出 2 天,而我想要 3 天,因为两个日期都应该包含在长度中。如果只是几天,我可以简单地将结果加 1,但我想使用 Diff 中的年/月/日结果,这些是在构造时确定的。

我发现获得所需结果的唯一方法是为开始和结束创建一个 DateTime(以获取格式化的日期和差异)。然后取结束日期时间,加上 1 天,然后算出长度。

这有点笨拙,但似乎没有办法告诉 DateTime Diff 在结果中包含开始日期和结束日期。

【问题讨论】:

  • 到目前为止,没有。同样的事情也适用于 DatePeriod。这肯定是一个缺点,但正如您所知,它是可以克服的。

标签: php datetime


【解决方案1】:

DateTime 封装了一个特定的时刻。 “昨天” 不是一个时刻,而是一个时间范围。 “明天”也是如此。

DateTime::diff() 不会忽略任何东西;它只是为您提供两个时间点之间的确切差异(以天、小时、分钟为单位)。

如果您想将“明天”和“昨天”之间的差异设为“3 天”,您可以从(“明天”最后一秒后的一秒)减去“昨天”的第一秒。

像这样:

// Always set the timezone of your DateTime objects to avoid troubles
$tz = new DateTimeZone('Europe/Bucharest');
// Some random time yesterday
$date1 = new DateTime('2016-07-08 21:30:15', $tz);
// Other random time tomorrow
$date2 = new DateTime('2016-07-10 12:34:56', $tz);

// Don't mess with $date1 and $date2;
// clone them and do whatever you want with the clones
$yesterday = clone $date1;
$yesterday->setTime(0, 0, 0);         // first second of yesterday (the midnight)
$tomorrow = clone $date2;
$tomorrow->setTime(23, 59, 59)               // last second of tomorrow
         ->add(new DateInterval('PT1S'));    // one second

// Get the difference; it is the number of days between and including $date1 and $date2
$diff = $tomorrow->diff($yesterday);

printf("There are %d days between %s and %s (including the start and end date).\n",
     $diff->days, $date1->format('Y-m-d'), $date2->format('Y-m-d')
);

【讨论】:

  • 您可以使用 DateTimeImmutable 代替克隆。
  • 当涉及到更改时,带有DateTimeImmutable 的“随心所欲”的部分会默默地创建新对象。不过,尽可能使用DateTimeImmutable 是一个很好的建议,尤其是当日期时间对象是函数参数时。
  • 是的,我认为 DateTime 对象是值对象,所以我更喜欢它们是不可变的,我已经犯了可变的 DateTime 对象几次创建奇怪的错误,直到我对它们更有经验: )
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多