Mack Trivedi
Mack Trivedi

Reputation: 13

How to get start date and end date of each week by providing only the year as input parameter in php?

I have a requirement where if I only pass the current year to a function then it should return all the start date and end date of all weeks of that year. I want this functionality in Laravel.

I have tried a code which I got online but I am not getting how to use it according to my requirement

   <?php        
    $var=2019;
    $date=Carbon::now();
    $date->setISODate($var,52);
    echo $date->startOfWeek();
    echo"<br>";
    echo $date->endOfWeek();
    ?>

I want something like this:(For current year) Week no 1: 2018-12-31 to 2019-01-06

Upvotes: 0

Views: 945

Answers (3)

Rob Mkrtchyan
Rob Mkrtchyan

Reputation: 220

function getWeeks($year, $format = 'Y-m-d H:i:s')
{
    $weekDates = [];

    // Get start of a year
    $start = Carbon::createFromDate($year)->startOfYear();

    // Skip week if the first day of week is in previous year
    // Uncomment next 2 lines if you want skip 2018 and get only weeks in 2019 :)
    // if($start->startOfWeek()->year != $year)
        // $start->addWeek();

    while($start->year == $year){
        $weekDates[] = [
            'start' => $start->startOfWeek()->format($format),
            'end' => $start->endOfWeek()->format($format)
        ];
        $start->addWeek();
    }

    return $weekDates;
}

dd(getWeeks(2019));

Upvotes: 0

Claudio
Claudio

Reputation: 5213

A php generic solution using the DateTime and DatePeriod classes, for PHP 7+.

function getWeeksOf(int $year, bool $roundEdgeDates = false) : array
{
    $weeks = [];
    $yearStart = (new \DateTime("{$year}-01-01 00:00:00"));
    $yearEnd = (new \DateTime("{$year}-12-31 23:59:59"));

    $dateRange = new \DatePeriod(
        (clone $yearStart)->modify('Monday this week'), 
        new \DateInterval('P1W'), 
        (clone $yearEnd)->modify('Sunday this week')
    );

    foreach($dateRange as $date){
        $weeks[] = [
            'start' => $date,
            'end' => (clone $date)->modify('+6 days 23 hours 59 minutes 59 seconds')
        ];
    }

    if ($roundEdgeDates) {
        $weeks[0]['start'] = $yearStart;
        $weeks[count($weeks) - 1]['end'] = $yearEnd;
    }

    return $weeks;
}

You can see it running here PHP Sandbox

Upvotes: 0

Umair Iftikhar
Umair Iftikhar

Reputation: 3

This will help

$var=2019;
$date=Carbon::now();
$i=1;
for($i; $i<=52; $i++){
  $date->setISODate($var,$i);
echo $date->startOfWeek();
echo"<br>";
echo $date->endOfWeek();
}

Upvotes: 0

Related Questions