Home > OS >  Round date up to next quarter
Round date up to next quarter

Time:01-26

I need to add 1 quarter to my date date("Y-m-d").

I have date 2018-03-05 next quarter will be 2018-04-01 not 2018-07-05 How i can do that please ?

Edit I have use this code but i have litle problem

while ($annee <= $annenow) {
            echo "$curMonth :: $annee   $annenow   <br>";
            if($curMonth<4)
                $curMonth=4;
            else if($curMonth<7)
                $curMonth=7;
            else if($curMonth<9)
                $curMonth=10;
            else if($curMonth<12)
                $curMonth=12;
            else
            {
                $curMonth=1;
                $anneedebut  ;
            }
            
            $curQuarter = ceil($curMonth / 3);
            $annee = "$anneedebut$curQuarter";
            
        }

The result is :

09 :: 20183 20221
12 :: 20184 20221
1 :: 20191 20221
4 :: 20192 20221
7 :: 20193 20221
10 :: 20194 20221
12 :: 20194 20221
1 :: 20201 20221
4 :: 20202 20221
7 :: 20203 20221
10 :: 20204 20221
12 :: 20204 20221
1 :: 20211 20221
4 :: 20212 20221
7 :: 20213 20221
10 :: 20214 20221
12 :: 20214 20221
1 :: 20221 20221

I have quater 4 repeate two time?

But my code is very big, im searshing to litle code if exist

CodePudding user response:

Take the month from the date, round it up to the next 3 (number of months in a quarter) and add 1 (since we're working with a 1-based system).

Then set the new parameters to the 1st of the next quarter month

$date = new DateTimeImmutable("2018-03-05");

$month = (int) $date->format("m");
$nextQuarterMonth = ceil($month / 3) * 3   1;

$nextQuarter = $date->setDate($date->format("Y"), $nextQuarterMonth, 1);

echo $nextQuarter->format("Y-m-d");

PHP's DateTime is smart enough to treat the 13th month as January in the next year if your original date is in the last quarter.

Demo ~ https://3v4l.org/fCWWQ

CodePudding user response:

//Months rounded up to the next higher interval
function roundUpMonth(string $date, int $numberMonth = 3) : string
{
  $dt = date_create($date);
  $month = $dt->format('Y') * 12   $dt->format('n');
  $month -= ($month-1)%$numberMonth - $numberMonth;
  return $dt->setDate(0,$month,1)->format('Y-m-d');
}

echo roundUpMonth("2018-03-05");  //2018-04-01
echo roundUpMonth("2018-02-05",1);  //2018-03-01
echo roundUpMonth("2018-05-07",2);  //2018-07-01
echo roundUpMonth("2018-07-05",6);  //2019-01-01
  •  Tags:  
  • Related