user1177437
user1177437

Reputation: 79

Calculate the first day of next month and quarter from today in PHP

For calculating the first dayof next month from today:

$firstDayNextMonth = date('Y-m-d', strtotime('first day of next month'));

How to calculate the first day of next quarter from today?

Thank you!

Upvotes: 2

Views: 166

Answers (2)

cOle2
cOle2

Reputation: 4784

As quarters can be different for different people I think you will need to define in code what your quarters are.

Then it is just a case of determining the current quarter and if the next quarter is in the new year or not:

//define our quarters
$quarters = array(
1 => '01-01',
2 => '04-01',
3 => '07-01',
4 => '10-01'
);

$month = date("n"); //get current month as a number

$currentQuarter = ceil($month / 3); //get the current quarter

echo 'We are currently in Q'.$currentQuarter.' of '.date("Y")."\n";

$nextQuarter = $currentQuarter+1;
    
//check if our quarter is defined, if not it is probably '5' which means next year
if (!isset($quarters[$nextQuarter])) { 
    $nextQuarter = 1;
    $year = date("Y")+1;
} else {
    $year = date("Y");
}

echo 'The first day of the next quarter is '.date("Y-m-d", strtotime($year.'-'.$quarters[$nextQuarter]));

Here's a working sample: https://3v4l.org/2Mo4o

Upvotes: 0

RiggsFolly
RiggsFolly

Reputation: 94682

There may be more elegant ways but this does the trick

$today = '2021-12-03';

$now = new DateTimeImmutable($today);
$nowMonth = (int) $now->format('m');
$yr = (int) $now->format('Y');

# Next quarter
echo 'Todays date is ' . $now->format('d/m/Y').PHP_EOL;
switch ($nowMonth){
    case 1:
    case 2:
    case 3:
        $quarter = new DateTimeImmutable("$yr/04/01");
        echo 'Next quarter is ' . $quarter->format('d/m/Y') . PHP_EOL;
        break;
    case 4:
    case 5:
    case 6:
        $quarter = new DateTimeImmutable("$yr/07/01");
        echo 'Next quarter is ' . $quarter->format('d/m/Y') . PHP_EOL;
        break;
    case 7:
    case 8:
    case 9:
        $quarter = new DateTimeImmutable("$yr/10/01");
        echo 'Next quarter is ' . $quarter->format('d/m/Y') . PHP_EOL;
        break;
    case 10:
    case 11:
    case 12:
        $yr++;
        $quarter = new DateTimeImmutable("$yr/01/01");
        echo 'Next quarter is ' . $quarter->format('d/m/Y') . PHP_EOL;
        break;
}

Upvotes: 1

Related Questions