-1

How could I get the date of the day Monday of a week having the year and number of week in the year?

For example, if the year is 2020 and the number of the week in the year is 01, the expected result is 2019-12-30

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Mario
  • 4,784
  • 3
  • 34
  • 50
  • 2
    What have you tried so far? It looks like you have enough SO reputation to know how this works :) – Cully Feb 06 '20 at 03:52
  • You need to specify which week numbering system you are using... – Nick Feb 06 '20 at 03:56
  • I don't have an idea how to do it. Right now I am investigating, specifically I am reading https://www.php.net/manual/en/datetime.formats.php – Mario Feb 06 '20 at 03:56
  • Nick, I am getting week number by `date('W', timestamp)`, I am getting formats from 01..52 – Mario Feb 06 '20 at 03:58
  • 1
    I think I get the solution, `date('Y-m-d', strtotime("{$year}-W{$week}-1"));` if year is 2020 and weed is 01 the result is 2019-12-30 – Mario Feb 06 '20 at 04:08

2 Answers2

3

Hope this is what you are looking for :)

<?php

$week_number = '06';
$year_number = '2020';

function getStartAndEndDate($week, $year) {
  $date = new DateTime();
  $date->setISODate($year, $week);
  for ($i=0; $i < 7; $i++) {
    $array[$i] = $date->format('Y-m-d');
    $date->modify('+1 days');
  }
  return $array;
}

$week_array = getStartAndEndDate($week_number,$year_number);

echo $week_array[0]; // 0 = monday, 1 = tuesday, and so on :)

?>
Niels
  • 1,005
  • 1
  • 8
  • 18
0
<?php
$week = 1;
$year = 2020;

$dateTime = date_create(sprintf("%04dW%02d",$year,$week)); //always a monday

echo $dateTime->format('Y-m-d');  //2019-12-30
jspit
  • 7,276
  • 1
  • 9
  • 17