Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Carbon get next occurrence of particular date from current date

Using Carbon with laravel 5.6.

I want write a code that give me next occurrence of date from current date.

E.g Give next 31st May date

Scenario 1 :
Input : $currentDate = '01-30-2019'; // MM-DD-YYYY format
Expected Output: $next31May = '05-31-2019';

Scenario 2 :
Input : $currentDate = '07-04-2019'; // MM-DD-YYYY format
Expected Output: $next31May = '05-31-2020';

Update:

I tried below code but not satisfy

<?php
public function nextOccurance()
{
    $now = Carbon::now();
    $month= $now->month;
    $year = $now->year;
    if($month > 6)
    {
         echo Carbon::createMidnightDate($year+1, 5, 31);
    }
    else
    {
        echo Carbon::createMidnightDate(null, 5, 31);
    }
    exit();
}
?>

Thank You in advance.

like image 748
urvisha Avatar asked Nov 01 '25 20:11

urvisha


1 Answers

public function nextOccurance()
{
    // the 31th of May of the current year
    $day = Carbon::createFromFormat('m-d', '05-31');
    $now = Carbon::now();
    // If today after $day
    if($now >= $day) {
       // Gat a next year
       $day->modify('next year');
    }

    echo $day->format('Y-m-d');
    exit();
}
like image 125
splash58 Avatar answered Nov 04 '25 11:11

splash58



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!