繁体   English   中英

php DateTime diff - 包括两个日期范围?

[英]php DateTime diff - include both dates in range?

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM