Vinod Kumar
Vinod Kumar

Reputation: 337

How to get date range for each week given month and year using PHP?

I am trying to get a week's date range(excluding saturday & sunday) for the given month and year.

For example:

$month = 5; $year = 2017;

Desired Output:

First Week : 
01-05-2017 to 05-05-2017

Second Week : 
08-05-2017 to 12-05-2017

Third Week : 
15-05-2017 to 19-05-2017

Fourth Week : 
22-05-2017 to 26-05-2017

Fifth Week:
29-05-2017 to 31-05-2017

I tried the script in following link but system crashes. http://sandbox.onlinephpfunctions.com/code/5f36a0af5401bfaa1847c8711f4fdbec67fed042

Upvotes: 2

Views: 961

Answers (1)

katona.abel
katona.abel

Reputation: 771

Here is a little script hope it helps

$month = 3;
$year = 2017;

$date = new \DateTime("now");
$date->setDate($year, $month, 1);
$date->setTime(0, 0, 0);

//last day of the month
$maxDay = intval($date->format("t"));

//getting the first monday
$dayOfTheWeek = intval($date->format("N"));
if($dayOfTheWeek != 1) {
    //print a partial week if needed
    $diff = 8 - $dayOfTheWeek;
    if($dayOfTheWeek <= 5) {
        $from = $date->format("Y-m-d");
        $diff2 = 5 - $dayOfTheWeek;
        $date->modify(sprintf("+%d days", $diff2));
        $to = $date->format("Y-m-d");
        echo sprintf("from: %s to %s\n", $from, $to);
        $diff -= $diff2;
    }
    $date->modify(sprintf("+%d days", $diff));
}

//iterate while we are in the current month
while(intval($date->format("n")) == $month) {
    $from = $date->format("Y-m-d");
    $date->modify("+4 days");
    if(intval($date->format("n")) > $month) {
        $date->setDate($year, $month, $maxDay);
    }
    $to = $date->format("Y-m-d");
    $date->modify("+3 days");

    echo sprintf("from: %s to %s\n", $from, $to);
}

Output:

from: 2017-05-01 to 2017-05-05
from: 2017-05-08 to 2017-05-12
from: 2017-05-15 to 2017-05-19
from: 2017-05-22 to 2017-05-26
from: 2017-05-29 to 2017-05-31

Output with partial first week

from: 2017-03-01 to 2017-03-03
from: 2017-03-06 to 2017-03-10
from: 2017-03-13 to 2017-03-17
from: 2017-03-20 to 2017-03-24
from: 2017-03-27 to 2017-03-31

Upvotes: 2

Related Questions