Home > Back-end >  How to get month name of custom range
How to get month name of custom range

Time:10-06

In my laravel application, The input is like this:

$from_year = 2019;
$from_month = 10;

$to_year = 2020;
$to_month = 4;

The expected output:

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

Thanks in advance.

CodePudding user response:

You could use couple methods that uses DateTime. First of all, you could create current and end date (with 1st day of the month) objects, and then calculate month difference using date_diff. Then it's just simple for with adding month interval.

Vanilla PHP solution would look like this:

$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);
}

Also, as you can see, I'm using the format method on DateTime object. More about the method you can read here.

CodePudding user response:

try following code

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

CodePudding user response:

$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)));
}

simple code with date() function

CodePudding user response:

This can be done using Carbon and CarbonPeriod libraries.

Here is how it goes:

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");
}

This will give you the result you want.

  • Related