carbon start of week sunday and endOfWeek Saturday not working

Viewed 4210

I need to select a particular users weekly top score. I am using Carbon and I forced Carbon startofWeek to SUNDAY and endOfWeek to SATURDAY.

Here is my DB data

id  user_id score   created_at            updated_at
43  33      88      2020-02-23 00:00:00     NULL
44  33      15      2020-02-24 00:00:00     NULL
45  33      42      2020-02-24 00:00:00     NULL
46  33      86      2020-02-25 00:00:00     NULL
47  33      100     2020-02-04 00:00:00     NULL 

Here is my code

     $week = GameScore::select(max('score')
             ->where('created_at', '>=', Carbon::now()->startOfWeek(Carbon::SUNDAY))
             ->where('created_at', '<=', Carbon::now()->endOfWeek(Carbon::SATURDAY))
             ->where('user_id', $user->id)
            ->get();

According to my data I need to get score 88 as result , because this score is obtained on 23rd Feb Sunday which is this weeks starting and till today all other scores are not greater than this.

3 Answers

In your code you need to specify the date format when comparing,

Carbon::now()->endOfWeek(Carbon::SATURDAY)->format('Y-m-d H:i:s');
$en = CarbonImmutable::now()->locale('en_US');


 $ar = CarbonImmutable::now()->locale('ar');



// We still can force to use an other day as start/end of week
   $start = $en->startOfWeek(Carbon::TUESDAY);
   $end = $en->endOfWeek(Carbon::SATURDAY);

var_dump($ar->endOfWeek()->format('Y-m-d H:i'));

Is working for me

You can set the starting day of the week by using the Carbon static function setWeekStartsAt and also can use that to work out the end of week day.


public static function getWeekStartAndEndDates($date, $startDayIndex = Carbon::SATURDAY)
    {
        $date = Carbon::parse($date);
        $date::setWeekStartsAt($startDayIndex);

        $from = $date->startOfWeek();

        $date::setWeekEndsAt($from->copy()->addDays(6)->dayOfWeek);
        $to = $date->copy()->endOfWeek();

        return ['from' => $from, 'to' => $to];
    }

Related