Nitin Nitin - 5 months ago 20
PHP Question

Finding date range for week for particular month and year

Suppose I have a date available with me:2016-07



I want to find date range of Week for the same like this:
2016-07-03 to 2016-07-09
2016-07-10 to 2016-07-16
2016-07-17 to 2016-07-23
2016-07-24 to 2016-07-30

how can i achieve this??
i have tried using mysql but failed now i m trying to doing php. can anybody help ???

Answer

This piece of code should do exactly what you want, if not please tell me or if you have questions

$date = "2016-07"; //Your date, can be any given date of this format
$monthAndYear = explode("-", $date);

$weeks = array();

$start = mktime(0, 0, 0, $monthAndYear[1], 1, $monthAndYear[0]);
$start -= 86400; //There are surely better ways

//find beginning if first week
do
{
    $start += 86400;// Add one day
    $tmp = date("N", $start);
}
while($tmp != 1);

//Get all weeks. If you want only those which are in the current month use this instead:
//while(date("n", ($start + 6 * 86400)) == $monthAndYear[1])
while(date("n", $start) == $monthAndYear[1])
{
    $date = date("Y-m-d", $start);
    $start += (6 * 86400);
    $date .= " to ".date("Y-m-d", $start);
    $weeks[] = $date;
    $start += 86400;
}

echo "<pre>";
var_dump($weeks);
echo "</pre>";

The output is this:

array(4) {
  [0]=>
  string(24) "2016-07-04 to 2016-07-10"
  [1]=>
  string(24) "2016-07-11 to 2016-07-17"
  [2]=>
  string(24) "2016-07-18 to 2016-07-24"
  [3]=>
  string(24) "2016-07-25 to 2016-07-31"
}

With the second while option the result will be the same because the 31th is the end of the month and also the end of a week.