Home > front end >  Get a range of dates for a specific week in a month
Get a range of dates for a specific week in a month

Time:10-18

I'm using Laravel and I want to generate a list of dates when I input its week order in a month. For example, when the input is "2nd week of October 2021" (or simply $week=2, $month = 10, $year = 2021) then it'll return dates from October 10th to October 16th. Can anybody help me?

CodePudding user response:

Have you tried whereBetween? For example :

$from = date('2021-01-01');
$to = date('2021-05-02');
Model::whereBetween('reservation_from', [$from, $to])->get();

CodePudding user response:

Check with following function. I guess that could give the results you need.

public function getWeekDates($year, $month, $week) {
    $dt = Carbon::create($year, $month, 1);

    $numberOfWeeks = floor($dt->daysInMonth / Carbon::DAYS_PER_WEEK);

    if(($numberOfWeeks   1) < $week) {
        return response()->json('Error : Invalid week provided.', 400);
    }

    $monthStartOfWeek = $dt->startOfWeek()->format('Y-m-d');
    $monthEndOfWeek = $dt->endOfWeek()->format('Y-m-d');

    $addDays = ($week-1) * Carbon::DAYS_PER_WEEK;

    $dt = $dt->addDays($addDays);

    $startOfWeek = $dt->startOfWeek()->format('Y-m-d');
    $endOfWeek = $dt->endOfWeek()->format('Y-m-d');

    $result = [
        'year' => $year,
        'month' => $month,
        'week' => $week,
        'start_of_week' => $startOfWeek,
        'start_of_week' => $startOfWeek,
        'end_of_week' => $endOfWeek,
    ];
 
    return $result;
}
  • Related