Shibbir
Shibbir

Reputation: 2031

PHP return current and previous month of given year

I want to show current and previous months of a given year like the below:

november-december 2019
september-october 2019
july-auguest 2019
may-june 2019
march-april 2019
january-february 2019

My current code:

$start = $month = strtotime('2019-02-01');
$end = strtotime( date( 'Y-m-d' ) );
while($month < $end)
{
    echo date('FY', $month);
    echo '<br/>';
    $month = strtotime("+1 month", $month);
}

can you tell me how can I do this? currently it's showing one month.

Updated code:

$start  =   $month = strtotime('2019-01-01');
$end    =   strtotime( date( 'Y-m-d' ) );
while($month < $end) {
    $current_prev_month = strtolower( date( 'F', $month ) . '-' . date( 'F', strtotime( '+1 month', $month ) ) . '-' . date( 'Y' ,$month ) );
    $month = strtotime("+2 month", $month);
    $current   = get_term_by( 'slug', $current_prev_month, 'issues' );
    if($current) {
    break;
    }
}

Now it's showing perfectly but can reverse it?

Upvotes: 0

Views: 42

Answers (2)

Dmitriy Gritsenko
Dmitriy Gritsenko

Reputation: 63

Try this

$currentDate = new \DateTime();
$startDate = \DateTime::createFromFormat('Y-m-d', '2019-02-01');

while ($startDate->getTimestamp() < $currentDate->getTimestamp()) {
    echo $currentDate->format('F-');
    $currentDate->modify('-1 month');
    echo $currentDate->format('F Y') . "<br/>\n";
    $currentDate->modify('-1 month');
}

Upvotes: 0

Nick
Nick

Reputation: 147146

Just output both months in each pass of the loop:

$month = strtotime('2019-02-01');
$end = strtotime( date( 'Y-m-01' ) );
while ($month < $end) {
    echo date('F-', $month);
    $month = strtotime("+1 month", $month);
    echo date('F Y', $month);
    echo '<br/>';
    $month = strtotime("+1 month", $month);
}

Output (as of 5/2/20):

February-March 2019
April-May 2019
June-July 2019
August-September 2019
October-November 2019
December-January 2020

Demo on 3v4l.org

To output the dates backward, you could use this code:

$end = strtotime('2019-02-01');
$month = strtotime( date( 'Y-m-01' ) );
while($month > $end)
{
    $month = strtotime("-2 month", $month);
    echo date('F-', $month);
    echo date('F Y', strtotime("+1 month", $month));
    echo '<br/>';
}

Output:

December-January 2020
October-November 2019
August-September 2019
June-July 2019
April-May 2019
February-March 2019

Demo on 3v4l.org

Upvotes: 1

Related Questions