[28, -6ren">
gpt4 book ai didi

php - 在 PHP 中将 2 个日期之间的天分组为月

转载 作者:行者123 更新时间:2023-12-04 15:50:53 25 4
gpt4 key购买 nike

假设我们有:

$startDt="10/28/2017";
$endDt="12/2/2017";

我想要将这些日期之间的几天分组为几个月。输出必须类似于:

[
"October"=>[28, 29, 30, 31],
"November"=>[1, ..., 30],
"December"=>[1,2]
]

不知道如何实现它。有什么建议吗?

最佳答案

您可以使用PHP的内置类DateTime , DateIntervalDatePeriod为了这;例如:

<?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
)

)

希望这有帮助:)

关于php - 在 PHP 中将 2 个日期之间的天分组为月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46854204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com