Davide Cavallini
Davide Cavallini

Reputation: 234

How-to get the start/end Mondays of the month in php

I need to include also the last Monday of the precedent month, and the first Monday of the next month.

Example

2016-01-25
2016-02-01
2016-02-08
2016-02-15
2016-02-22
2016-02-29
2016-03-07

I have this code so far:

function getAllDaysInAMonth($year, $month, $day = 'Monday', $daysError = 3) {
    $dateString = 'first ' . $day . ' of ' . $year . '-' . $month;
    if (!strtotime($dateString)) {
        throw new \Exception('"' . $dateString . '" is not a valid strtotime');
    }

    $startDay = new \DateTime($dateString);

    if ($startDay->format('j') > $daysError) {
        $startDay->modify('- 7 days');
    }

    $days = array();

    while ($startDay->format('Y-m') <= $year . '-' . str_pad($month, 2, 0, STR_PAD_LEFT)) {
        $days[] = clone($startDay);
        $startDay->modify('+ 7 days');
    }
    return $days;
}

Upvotes: 1

Views: 77

Answers (2)

Davide Cavallini
Davide Cavallini

Reputation: 234

Ok, resolved!

function getAllDaysInAMonth($year, $month, $day = 'Monday', $daysError = 3) {
$dateString = 'first ' . $day . ' of ' . $year . '-' . $month;

if (!strtotime($dateString)) {
    throw new \Exception('"' . $dateString . '" is not a valid strtotime');
}

$startDay = new \DateTime($dateString);

if ($startDay->format('j') > $daysError) {
    $startDay->modify('- 7 days');
}

$days = array();

$lastMonday = new DateTime("last Monday of last month");
$nextMonday = new DateTime("first Monday of next month");


$days[] = clone($lastMonday);

while ($startDay->format('Y-m') <= $year . '-' . str_pad($month, 2, 0, STR_PAD_LEFT)) {
    $days[] = clone($startDay);
    $startDay->modify('+ 7 days');
}

$days[] = clone($nextMonday);


return $days;
}

Upvotes: 1

Adrian P.
Adrian P.

Reputation: 175

Try this :

$lastMonday = new DateTime("last Monday of last month");
$nextMonday = new DateTime("first Monday of next month");

echo 'Last Monday : '.$lastMonday->format('Y-m-d').'<br />';
echo 'First Monday : '.$nextMonday->format('Y-m-d');

Upvotes: 0

Related Questions