0

I have the following problem.

In the employees table I store the free days of the week that has an employee. For example The free days of John are always on Monday.

So, I want to get all the dates for a year that falls on Monday.

For example in this month (Today is the 24-05-2016) the dates are for Monday:

All this dates are on Mondays:
02-05-2016,
09-05-2016,
16-05-2016,
23-05-2016,
30-05-2016
 and so on.

Is there a way to do that in PHP?

Thanks

juanpscotto
  • 990
  • 1
  • 13
  • 32
  • This is probably better suited to handle in your database, depending on what flavor of database you're using. In PHP you're going to have to do some kind of loop or iteration. In MS SQL, for example, no loop is required. – devlin carnate May 24 '16 at 21:33
  • Have a look at http://stackoverflow.com/a/12554714/2003600, this could help you in the right direction. – Milanzor May 24 '16 at 21:33

1 Answers1

1

The interval is always 7 days, so just work out the start date as a DateTime object for the first "monday" of the year, end date as a year from then, and use DatePeriod to loop through that date range with an interval of every 7 days

$startDate = new DateTime('2016-01-01');
$startDate->modify('first monday');
$endDate = clone $startDate;
$endDate = $endDate->add(new DateInterval('P1Y'));

$interval = new DateInterval('P7D');

$period = new DatePeriod($startDate, $interval, $endDate);
foreach ($period as $date) {
    echo $date->format('Y-m-d').PHP_EOL;
}

Adjust start and end dates to taste

Mark Baker
  • 209,507
  • 32
  • 346
  • 385