计算两个日期之间日期(例如第 14 个)的出现次数
count occurrence of date (e.g 14th) between two dates
如何计算两个日期之间一个月的第 14 天的出现次数
例如在 07.05.2018 和 04.07.2018 之间
我有 2 次出现第 14 次
试试这个。请注意,我已经更改了你的日期格式,但如果你真的喜欢自己的格式,你可以只做 createFromFormat
。
$startDate = new DateTime('2018-05-07');
$endDate = new DateTime('2018-07-04');
$dateInterval = new DateInterval('P1D');
$datePeriod = new DatePeriod($startDate, $dateInterval, $endDate);
$fourteenths = [];
foreach ($datePeriod as $dt) {
if ($dt->format('d') == '14') { // Note this is loosely checked!
$fourteenths[] = $dt->format('Y-m-d');
}
}
echo count($fourteenths) . PHP_EOL;
var_dump($fourteenths);
在此处查看实际效果:https://3v4l.org/vPZZ0
编辑
这可能不是最佳解决方案,因为您要遍历日期期间的每一天并检查它是否是第十四天。可能更容易的是将开始日期修改为下一个 14 日,然后检查间隔 P1M
.
你根本不需要循环。
这是一个根本不循环的解决方案,并且使用与 DateTime 相反的更少内存和性能饥饿日期。
$start = "2018-05-07";
$end = "2018-07-04";
$times = 0;
// Check if first and last month in the range has a 14th.
if(date("d", strtotime($start)) <= 14) $times++;
if(date("d", strtotime($end)) >= 14) $times++;
// Create an array with the months between start and end
$months = range(strtotime($start . "+1 month"), strtotime($end . "-1 month"), 86400*30);
// Add the count of the months
$times += count($months);
echo $times; // 2
如何计算两个日期之间一个月的第 14 天的出现次数
例如在 07.05.2018 和 04.07.2018 之间
我有 2 次出现第 14 次
试试这个。请注意,我已经更改了你的日期格式,但如果你真的喜欢自己的格式,你可以只做 createFromFormat
。
$startDate = new DateTime('2018-05-07');
$endDate = new DateTime('2018-07-04');
$dateInterval = new DateInterval('P1D');
$datePeriod = new DatePeriod($startDate, $dateInterval, $endDate);
$fourteenths = [];
foreach ($datePeriod as $dt) {
if ($dt->format('d') == '14') { // Note this is loosely checked!
$fourteenths[] = $dt->format('Y-m-d');
}
}
echo count($fourteenths) . PHP_EOL;
var_dump($fourteenths);
在此处查看实际效果:https://3v4l.org/vPZZ0
编辑
这可能不是最佳解决方案,因为您要遍历日期期间的每一天并检查它是否是第十四天。可能更容易的是将开始日期修改为下一个 14 日,然后检查间隔 P1M
.
你根本不需要循环。
这是一个根本不循环的解决方案,并且使用与 DateTime 相反的更少内存和性能饥饿日期。
$start = "2018-05-07";
$end = "2018-07-04";
$times = 0;
// Check if first and last month in the range has a 14th.
if(date("d", strtotime($start)) <= 14) $times++;
if(date("d", strtotime($end)) >= 14) $times++;
// Create an array with the months between start and end
$months = range(strtotime($start . "+1 month"), strtotime($end . "-1 month"), 86400*30);
// Add the count of the months
$times += count($months);
echo $times; // 2