1

Suppose I have a timetable for a particular subject with subject code say(MI132). Now as per the timetable, the classes of MI132 are on Monday, Tuesday and Wednesday each week for a session. The session might start on the date say(12/01/2019). Now the first class for the subject starts on 12/01/2019 and the last class is on 30/11/2019. What I want is an array of dates on which this particular subject MI132 will have classes? Now I know how I can write the code for this in PHP. It would be a code of say 50-100 lines. I have the logic with me. But do we have an in-built function which gives me an array of dates(for a duration 12/01/2019-31/11/2019) when I provide it the days only?

Any other approach will also be appreciated. I only need the array of dates on which that subject will have a class.

1 Answers1

1

It's not a single class, like you ask, but there are builtin classes that will allow you to do what you need in a fraction of the code: DateInterval and DatePeriod

$start = '12/01/2019'; $end ='31/01/2019';

$start = DateTime::createFromFormat('d/m/Y', $start);
$end = DateTime::createFromFormat('d/m/Y', $end);

$each = new DateInterval('P1D');
$period = new DatePeriod($start, $each, $end);

$dates = [];
foreach ($period as $date) {
    // Check if its between monday and wednesday 
    $weekday = intval($date->format('N'));
    if ($weekday >= 1 && $weekday <= 3)
       $dates[] = $date;
}

print_r($dates);
msg
  • 7,863
  • 3
  • 14
  • 33
  • Thanks. Can we also make the code to return the day along with the date? – Amar Parajuli Jun 15 '19 at 16:12
  • 1
    @AmarParajuli I'm not sure what you mean. Do you mean `$weekday`? You can call `format()` again on the date when printing it, but sure, you can change the structure of the `$dates` array. – msg Jun 15 '19 at 16:17