gpt4 book ai didi

php - 在 PHP 中每个月的所有日期都在两个日期之间

转载 作者:可可西里 更新时间:2023-10-31 23:01:31 24 4
gpt4 key购买 nike

我怎样才能像这样在数组中获取两天之间每个月的所有天数

$dateStart = "2016/12/14"; 
$dateFin = "2017/04/21"

[2016/12/14 - 2016/12/31] => 17 days
[2017/01/01 - 2017/01/31] => 31 days
[2017/02/01 - 2017/02/28] => 28 days
[2017/03/01 - 2017/03/30] => 31 days
[2017/04/01 - 2017/04/21] => 21 days

最佳答案

您可以使用函数 cal_days_in_month加上 DateTime 类:

<?php
$dateStart = new DateTime("2016/12/14");
$dateFin = new DateTime("2017/04/21");
$firstDay = $dateStart->format('Y/m/d');
$lastDay = $dateStart->format('Y/m/t');
$totalMonths = $dateStart->diff($dateFin)->m + ($dateStart->diff($dateFin)->y*12);
$result = [];
for ($i = 0; $i <= $totalMonths; $i++)
{
if ($i != 0){
$dateStart->modify('first day of next month');
$firstDay = $dateStart->format('Y/m/d');
$dateStart->modify('last day of month');
$lastDay = $dateStart->format('Y/m/t');
}

$nextDate = explode('/', $firstDay);

$totalDays = cal_days_in_month(CAL_GREGORIAN, $nextDate[1], $nextDate[2]);
if ($i == 0){
$totalDays -= $dateStart->format('d');
} else if ($i == $totalMonths) {
$totalDays = $dateFin->format('d');
}

$result["$firstDay - $lastDay"] = $totalDays;
}

var_dump($result);

缺乏改进,但可以满足您的要求。

常规改进,检查如下:

$dateStart = new DateTime("2016/12/14");
$dateFin = new DateTime("2017/04/21");
$totalMonths = $dateStart->diff($dateFin)->m + ($dateStart->diff($dateFin)->y*12);
$result = [];
for ($i = 0; $i <= $totalMonths; $i++)
{
if ($i != 0){
$obj = $dateStart->modify('first day of next month');
}

$firstDay = $dateStart->format('Y/m/d');
if ($i == $totalMonths){
$lastDay = $dateFin->format('Y/m/d');
} else {
$lastDay = $dateStart->format('Y/m/t');
}
$firstDayObj = strtotime($firstDay);
$lastDayObj = strtotime($lastDay);
$totalDays = (int) ceil(($lastDayObj - $firstDayObj) / 86400);
$totalDays = ((int) $dateStart->format('d') == 1) ? $totalDays + 1 : $totalDays;
$result["$firstDay - $lastDay"] = $totalDays;
}

var_dump($result);

//array(5) { ["2016/12/14 - 2016/12/31"]=> int(17) ["2017/01/01 - 2017/01/31"]=> int(31) ["2017/02/01 - 2017/02/28"]=> int(28) ["2017/03/01 - 2017/03/31"]=> int(31) ["2017/04/01 - 2017/04/21"]=> int(21) }

关于php - 在 PHP 中每个月的所有日期都在两个日期之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44282688/

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