在我的 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'
]
提前致谢。
您可以使用几种使用DateTime
. 首先,您可以创建当前和结束日期(每月的第一天)对象,然后使用date_diff
. 然后添加月份间隔就很简单了。
Vanilla 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);
}
另外,如您所见,我在对象上使用该format
方法。DateTime
您可以在此处阅读有关该方法的更多信息。
尝试以下代码
<?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);
?>
$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"));
}