Ansari Khalid Ansari Khalid - 3 months ago 9
PHP Question

get start and end date of month by week number of the month in php

How do I compute the start and end date of a week by month, year, and week number? The year is a 4-digit integer, such as 2016; the month is an integer, range 1-12; the week is an integer in the range 1-5.

I already have this code block:

function getStartAndEndDate($week, $year)
{
$time = strtotime("1 $year", time());
$day = date('w', $time);
$time += ((7 * $week) + 1 - $day) * 24 * 3600;
$return[0] = date('Y-n-j', $time);
$time += 6 * 24 * 3600;
$return[1] = date('Y-n-j', $time);
return $return;
}


How can I use or rewrite this function?

Answer

As for your function above in the question I have no idea, but assuming the week starts on Monday and ends on Sunday something like this might work

function getFirstandLastDate($year, $month, $week) {

    $thisWeek = 1;

    for($i = 1; $i < $week; $i++) {
        $thisWeek = $thisWeek + 7;
    }

    $currentDay = date('Y-m-d',mktime(0,0,0,$month,$thisWeek,$year));

    $monday = strtotime('monday this week', strtotime($currentDay));
    $sunday = strtotime('sunday this week', strtotime($currentDay));

    $weekStart = date('d M y', $monday);
    $weekEnd = date('d M y', $sunday);

    return $weekStart . ' - ' . $weekEnd;
}

echo getFirstandLastDate( 2016, 1, 1 );