Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding next 13 Mondays and the last Monday

Tags:

date

php

datetime

I have the following code that return's the next 13 Mondays from today's date.

for($i=1; $i<=13; $i++){
    echo date("Y-m-d", strtotime('+'.$i.' Monday'))."<br>";
}

I want to be able to amend this so it not only shows the next 13 Mondays but the Monday that has just past.

I tried amending the code as follows but I then get two instances of the next Monday returned.

for($i=-1; $i<=13; $i++){
echo date("Y-m-d", strtotime('+'.$i.' Monday'))."<br>";
}

Data returned.

2015-04-13
2015-04-20  //<--
2015-04-20
2015-04-27
2015-05-04
2015-05-11
2015-05-18
2015-05-25
2015-06-01
2015-06-08
2015-06-15
2015-06-22
2015-06-29
2015-07-06
2015-07-13

Any ideas on how I achieve this?

like image 797
John Higgins Avatar asked Apr 17 '15 08:04

John Higgins


People also ask

How do you find Mondays between two dates?

To find the first Monday, subtract one from the start date (to cover for starting on Monday). Then find the next Monday.

What weekday is the 13th?

On average, there is a Friday the 13th once every 212.35 days. Friday the 13ths occurs with an average frequency of 1.7218 per year or about 3477 since the year 1 CE.


3 Answers

I would do it like this:

for($i =- 1; $i <= 13; $i == 0 ? $i += 2 : $i++){
    echo date("Y-m-d", strtotime("$i Monday")) . "<br>";
}

Using a ternary operator to check if $i is 0 - and if, increase it by 2 instead of 1 :)

like image 92
Marc Avatar answered Oct 13 '22 17:10

Marc


Try this:

echo date("Y-m-d", strtotime('-1 Monday'))."<br>";
for($i=1; $i<=13; $i++){
    echo date("Y-m-d", strtotime('+'.$i.' Monday'))."<br>";
}

Or you need only one for statement?

like image 39
2kai Avatar answered Oct 13 '22 17:10

2kai


function mondays() {
    $begin = new DateTime('last monday');
    $end = clone $begin;
    $end->add(new DateInterval('P14W')); // next 13 + last

    $interval = new DateInterval('P1W');
    $daterange = new DatePeriod($begin, $interval ,$end);

    foreach($daterange as $date){
        yield $date;
    }
}


foreach(mondays() as $date){
    echo $date->format("Y-m-d"), PHP_EOL;
}
like image 33
Mark Baker Avatar answered Oct 13 '22 17:10

Mark Baker