0

我曾经DateTime得到两个日期的差异。直接来自 PHP 文档示例:

$date1 = new DateTime('2012/03/15');
$date2 = new DateTime('2012/6/9');
$interval = $date1->diff($date2,true);
$days = $interval->format('%R%a days');

这将导致+86 days,我想知道我在哪里可以得到那些%R%a我不知道他们的意思的人的参考,但我只是通过看到那个%R = +而知道%a is number of days

其次,现在通过拥有该值86,我至少可以拥有一个变量,我可以用它来说明这一点,$date1并且$date2不在 3 个月的长度内(3 个月至少是 90 天)。我可以简单地使用if-else它,但是为了精确起见,是否有另一种方法(内置 PHP 函数或库)来确定我拥有的价值在 3 个月内?

4

3 回答 3

2

您也可以在文档中找到它:

%   Literal %   %
Y   Years, numeric, at least 2 digits with leading 0    01, 03
y   Years, numeric  1, 3
M   Months, numeric, at least 2 digits with leading 0   01, 03, 12
m   Months, numeric 1, 3, 12
D   Days, numeric, at least 2 digits with leading 0 01, 03, 31
d   Days, numeric   1, 3, 31
a   Total number of days as a result of a DateTime:diff() or (unknown) otherwise    4, 18, 8123
H   Hours, numeric, at least 2 digits with leading 0    01, 03, 23
h   Hours, numeric  1, 3, 23
I   Minutes, numeric, at least 2 digits with leading 0  01, 03, 59
i   Minutes, numeric    1, 3, 59
S   Seconds, numeric, at least 2 digits with leading 0  01, 03, 57
s   Seconds, numeric    1, 3, 57
R   Sign "-" when negative, "+" when positive   -, +
r   Sign "-" when negative, empty when positive -,
于 2012-11-21T09:37:18.833 回答
2
  1. 检查文档以获取DateTime::diff.
  2. 看到它返回一个DateInterval,单击链接到它的文档
  3. 阅读format方法的文档。

用于if ($interval->format('%m') > 3)测试是否超过三个月。请注意,这只是间隔的月份部分,例如“2 年,3 个月”中的“3”。还要考虑年份。你不应该只使用天数,因为一个月没有固定的天数。90天和3个月不是一回事。

于 2012-11-21T09:38:53.900 回答
1

http://www.php.net/manual/en/dateinterval.format.php用于文档

$months = 3;
if ($interval->format('%m') < $months) {
   echo "Less than $months months";
}
于 2012-11-21T09:38:09.907 回答