So I came up with a situation where I want to retrieve the dates that fall under a specific week number. I tried some methods but unfortunately, they did not work out.
So first I am getting the week number of the date that I have/selected/inputed.
$week_number = date('W', strtotime(23/08/2022)) //Will output 34
What I tried to do... But the dates that are being returned are random and not what I am expecting
$dates = array();
for($i = 1; $i <=7; $i ){
$dates[$i] = date('Y-m-d', strtotime($selected_date . ' -' . ($week_number) . ' days ' .
$i . ' days'));
}
What I am expecting:
[1] => 2022-08-22
[2] => 2022-08-23
[3] => 2022-08-24
[4] => 2022-08-25
[5] => 2022-08-26
[6] => 2022-08-27
[7] => 2022-08-28
I don't know if this is a duplicate question but I cannot find what I am looking for.
CodePudding user response:
I just did something very similar not to long ago. I had to find the date of a day in a week in a certain year. My solution was:
function getDateForWeekDay($year, $weekNo, $dayOfWeekNo)
// return the exact date of this weekday, using ISO 8601
{
$date = new DateTime();
$date->setISODate($year, $weekNo, $dayOfWeekNo);
return $date->format('Y-m-d');
}
for instance, echo getDateForWeekDay(2020, 34, 1);
will return 2020-08-17
, see: https://3v4l.org/bkjUj
See the PHP manual: DateTime::setISODate()
You can easily expand this to generate your array.
for ($day = 1; $day <= 7; $day ) {
$dates[$day] = getDateForWeekDay(2020, 34, $day);
}
print_r($dates);
Which returns the wanted result. See: https://3v4l.org/iDKOu
CodePudding user response:
You can use this to get monday and sunday of a week :
$day = 1; // 1 to 6, monday to saturday.
$dayDate = new \DateTime();
$dayDate->setISODate($date->format('Y'), $date->format('W'), $day);