2

I need to get certain weekdays within a period of time. Weekdays can be only one ore more, e.g. only all Mondays or all Mondays, Tuesdays and Wednesdays.

I would like to use DatePeriod together with DateInterval::createFromDateString

DateInterval::createFromDateString is accepting Relative Formats.

How can I pass one or more weekdays as relative formats into DateInterval::createFromDateString. Is this possible at all?

In relative formats I can't find a format "every" that would make it possible to do

$i = DateInterval::createFromDateString('every Monday');
gebeer
  • 703
  • 6
  • 8
  • 1
    Relative formats only go so far. You'll have to write your own logic to get these dates. – John Conde Oct 21 '14 at 12:40
  • ["Monday"](http://php.net/manual/de/datetime.formats.relative.php) – Wrikken Oct 21 '14 at 12:41
  • @John Conde ok, that's what I thought. Just wanted to make sure. – gebeer Oct 21 '14 at 12:45
  • @Wrikken Will this give evry Monday within my defined period? And can I pass multiple days like "Monday or Tuesday or Wednesday"? – gebeer Oct 21 '14 at 12:46
  • Hm, it should according to the docs _"dayname Moves to the next day of this name."_, but it seems to fail miserably here... – Wrikken Oct 21 '14 at 12:56
  • And it wouldn't help you with multiple days needed as well. Might not be ideal for a `DatePeriod`, you may have to resort to just adding a day to a `DateTime` in a for loop, and validating or discarding (`continue;`) certain non-valid dates. – Wrikken Oct 21 '14 at 13:01
  • @Wrikken Yeah, it is failing here, too. Seems not possible to do this with relative formats. But thanks for trying – gebeer Oct 21 '14 at 13:18

1 Answers1

9

Thanks to all comments and answers I now know that I cannot pass a relative format like "every Monday" to DateInterval::createFromDateString.

But something like this works for my scenario:

$start = new DateTime('2014-11-01');
$end = new DateTime('2014-12-01');
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
$mydays = array('1', '3', '5');

foreach($period as $date) {
    if(in_array($date->format('N'), $mydays)) {
    //do something for Monday, Wednesday and Friday
    }
}
gebeer
  • 703
  • 6
  • 8