Knighto05 Knighto05 - 4 months ago 42
SQL Question

php list of weeks between two dates

I need to get the list of weeks between two dates (week of the dates included) with php or mysql.

Example:

Start date: 2016-07-05

End date: 2016-07-28

Expected output:

"week of 2016-07-04"
"week of 2016-07-11"
"week of 2016-07-18"
"week of 2016-07-25"


Please, help!

EDIT

It is for a timetable, I have two dates in a database which are the interval of the school year. I need to get the weekdays (the [monday-friday] interval) so that I can put it in a select field.

PS: Please, I need to know why you downvoted the question, I'm still new and may be I did some mistakes :/

SOLVED

Thank you Keyur Buch, I took your answer and altered it a bit using a function I saw here http://stackoverflow.com/a/29977061/4685497

Finally this is the answer:

$date1 ='2016-07-05';
$date2 ='2016-07-28';

//calculate week
$weekDiff = date('W', strtotime($date2)) - date('W', strtotime($date1));

$i=0;
for($i=1;$i<=$weekDiff+1;$i++)
{
if($i==1)
{
$nw=getMonday(new DateTime($date1));
}else{
$nw = date('Y-m-d',strtotime($nw . "+7 days"));
}

echo "week of ".$nw;
echo "<br>";
}

function getMonday(DateTime $date){
$outdate = clone($date);
$day = $date->format("w"); // get the weekday (sunday is 0)
$outdate->sub(new DateInterval("P".$day."D")); // this gives the sunday date
$temp = $outdate->format('Y-m-d H:i:s');
$monday = date('Y-m-d',strtotime($temp . "+1 days"));// incrementing sunday date in order to get monday date
return $monday;
}

Answer

Pl. try this code

$date1 ='2016-07-05';
$date2 ='2016-07-28';
$d1=strtotime($date1);
//calculate week
$weekDiff = date('W', strtotime($date2)) - date('W', strtotime($date1));
//echo $weekDiff;
$i=0;
for($i=1;$i<=$weekDiff;$i++)
{
    if($i==1)
    {
        $nw=$date1;
    }
    $nw = date('Y-m-d',strtotime($nw . "+7 days"));
    echo "week of ".$nw;
    echo "<br>";
}