Home » Php » php – Carbon: Get start and end date of week when knowing week in year and year

php – Carbon: Get start and end date of week when knowing week in year and year

Posted by: admin July 12, 2020 Leave a comment

Questions:

Carbon provides the function weekOfYear to get the week of the year as integer. However I need to go the other way round to get the a date based on the year + the week of the year.

Carbon::now()->weekOfYear(); // todays week of the year

E.g.

  • year: 2016
  • week of year: 42

As a result i need the start and end date of this given week. However i cannot find a fitting function in the Carbon docs

How to&Answers:

Carbon is a wrapper for PHP’s DateTime, so you can use setISODate:

$date = Carbon::now(); // or $date = new Carbon();
$date->setISODate(2016,42); // 2016-10-17 23:59:59.000000
echo $date->startOfWeek(); // 2016-10-17 00:00:00.000000
echo $date->endOfWeek(); // 2016-10-23 23:59:59.000000