让我们说:
$startDt="10/28/2017";
$endDt="12/2/2017";
我希望在这些日期之间将数天分为几个月。输出必须如下:
[
"October"=>[28, 29, 30, 31],
"November"=>[1, ..., 30],
"December"=>[1,2]
]
无法弄清楚如何实现它。有什么建议吗?
答案 0 :(得分:5)
您可以使用PHP的内置类DateTime
,DateInterval
和DatePeriod
来实现此目的; e.g:
<?php
$start = new DateTime('10/28/2017');
$end = new DateTime('12/2/2017');
$interval = new DateInterval('P1D'); // 1 day
$period = new DatePeriod($start, $interval, $end);
$days = [];
foreach ($period as $dt) {
$month = $dt->format('F');
$day = $dt->format('j');
$days[$month][] = $day;
}
print_r($days);
Here is the documentation about date formatting
请注意,如果时间相同,DatePeriod
会进入但排除最后一个日期(这是这种情况,因此您可能希望修改结束日期以解决此问题 - 添加秒应该可以做到这一点;例如:
$end = new DateTime('12/2/2017');
$end->modify('+1 second');
// or $end->setTime(0, 0, 1); H/T to @ishegg
$period = new DatePeriod($start, $interval, $end);
// etc.
这会产生:
Array
(
[October] => Array
(
[0] => 28
[1] => 29
[2] => 30
[3] => 31
)
[November] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
[10] => 11
[11] => 12
[12] => 13
[13] => 14
[14] => 15
[15] => 16
[16] => 17
[17] => 18
[18] => 19
[19] => 20
[20] => 21
[21] => 22
[22] => 23
[23] => 24
[24] => 25
[25] => 26
[26] => 27
[27] => 28
[28] => 29
[29] => 30
)
[December] => Array
(
[0] => 1
)
)
希望这会有所帮助:)