How to show days of the first week of the year?

Viewed 46

Hello i have this code:

$anno = 2020;
$settimana = 53;
$anno2 = 2021;
$settimana2 = 1;

for($i = 1; $i <= 7; $i++){
    $giorno = date('d/m/Y', strtotime($anno."W".$settimana.$i));
    echo $giorno."<br>";
}

echo "<br><hr><br>";

for($i = 1; $i <= 7; $i++){
    $giorno2 = date('d/m/Y', strtotime($anno2."W".$settimana2.$i));
    echo $giorno2."<br>";
}

This is the output of first loop:

28/12/2020
29/12/2020
30/12/2020
31/12/2020
01/01/2021
02/01/2021
03/01/2021

This is the output of the second loop

15/03/2021
22/03/2021
29/03/2021
05/04/2021
12/04/2021
19/04/2021
26/04/2021

But i wait this output

04/01/2021
05/01/2021
06/01/2021
07/01/2021
08/01/2021
09/01/2021

How can i resolve the problem?

1 Answers

You can try this function Modify this function as your requirements. Create array of whole week by running a loop from 1 to 6 days. you will get your required result.

function getStartAndEndDate($week, $year) {
  $dto = new DateTime();
  $dto->setISODate($year, $week);
  $ret['week_start'] = $dto->format('Y-m-d');
  $dto->modify('+6 days');
  $ret['week_end'] = $dto->format('Y-m-d');
  return $ret;
}

$week_array = getStartAndEndDate(1,2021);
print_r($week_array);

//output
Array
(
    [week_start] => 2021-01-04
    [week_end] => 2021-01-10
)

EDIT: 

 I checked your code and i think problem is with $settimana2 = 1; change this variable to $settimana2 = 01;

Related