Search code examples
phplaraveldatephp-carbon

I Want To Get the First or Last Friday in a Month in Laravel using Carbon


I'm using laravel8. I want to get a date of last Friday and first Friday in a month. I'm using Carbon.

I tried the below code snippet, but it gave me the carbon instance along with the date of previous Friday

    $searchDay = 'Friday';
    $searchDate = new Carbon(); //or whatever Carbon instance you're using
    $last = Carbon::createFromTimeStamp(strtotime("last $searchDay", $searchDate->timestamp));

    dd($last);

Today's date is 16-Sep-2022 and the Expected result should be 30-sep-2022 but that snippet gives me a result of 09-Sep-2022(the previous Friday date).


Solution

  • That snippet works perfectly for me:

    Solution 1:

        $month = (new Carbon())->monthName;       //September
        $year= (int)Carbon::now()->format('Y');   //2022  
        $last = Carbon::parse("Last friday of {$month} {$year}");
    

    Solution 2:

     $last = Carbon::parse("Last friday of this month");
    

    In this snippet, I fetch the current month's name and the current year. By putting those values in Carbon:parse() statement. I'm able to get every month's last Friday date using Carbon.

    If you want to get first Friday then you can replace last keyword with first in Carbon::parse() statement.

    For Second Solution Credit Goes to: thread