如何获取自定义范围的月份名称

How to get month name of custom range

在我的 laravel 申请中, 输入是这样的:

$from_year = 2019;
$from_month = 10;

$to_year = 2020;
$to_month = 4;

预期输出:

months = [
'October 2019', 'November 2019', 'December 2019', 'January 2020', 'February 2020', 'March 2020', 'April 2020'
]

提前致谢。

尝试以下代码

   <?php

$from_year = 2019;
$from_month = 10;

$to_year = 2020;
$to_month = 4;
$arr = [];
for($i=$from_year;$i<$to_year;$i++) {
    
    if($i==$from_year){
        $fmonth = $from_month;
    }else{
        $fmonth = 1;
    }
    for($j=$fmonth;$j<=12;$j++){
        array_push($arr,DateTime::createFromFormat('!m', $j)->format('F'). " ".$i);
    }
}
    for($i=1;$i<=$to_month;$i++){
        array_push($arr,DateTime::createFromFormat('!m', $i)->format('F'). " ".$to_year);
    }

print_r($arr);
?>

您可以使用一些使用 DateTime 的方法。首先,您可以创建当前日期和结束日期(每月的第一天)对象,然后使用 date_diff 计算月差。然后加上月份间隔就简单了。

普通 PHP 解决方案如下所示:

$from_year = 2019;
$from_month = 10;

$to_year = 2020;
$to_month = 4;

$date = new DateTime("$from_year-$from_month-01");
$diff = date_diff($date, new DateTime("$to_year-$to_month-01"));
$monthsDiff = $diff->y * 12 + $diff->m;
$interval = new DateInterval('P1M');

$monthsArray = [];

for($i = 0; $i <= $monthsDiff; $i++){
    $monthsArray[] = $date->format('F Y');
    $date->add($interval);
}

此外,如您所见,我在 DateTime 对象上使用了 format 方法。有关方法的更多信息,您可以阅读 here.

$startDate = date($from_year.'-'.$from_month.'-01');
$diff = (($to_year - $from_year) * 12) + ($to_month - $from_month);

$months = [];
for($i=0;$i<=$diff;$i++) {
    $months[] = date('F Y', strtotime('+'.$i.' month', strtotime($startDate)));
}

具有date()功能的简单代码

这可以使用 Carbon 和 CarbonPeriod 库来完成。

事情是这样的:

use Carbon\Carbon;
use Carbon\CarbonPeriod;

$from_year = 2019;
$from_month = 10;

$to_year = 2020;
$to_month = 4;

$fromDate = new Carbon('1-' . $from_month . '-' . $from_year);
$toDate = new Carbon('1-' . $to_month . '-' . $to_year);

$differnces = CarbonPeriod::create($fromDate, '1 month', $toDate);

$differenceInDates = [];

foreach ($differnces as $differnce) {
    $differenceInDates[] = $differnce->format("M F");
}

这会给你想要的结果。

$from_year = 2019;
$from_month = 10;

$to_year = 2020;
$to_month = 4;

$start = strtotime($from_year . "-" . $from_month . "-01");
$end = strtotime($to_year . "-" . $to_month . "-01");
$months = [date("F Y",$start)];

while(strtotime(end($months)) < $end){
    $months[] = date("F Y",strtotime(end($months) . " +1 month"));
}