codedudey codedudey - 5 months ago 23
PHP Question

PHP How to extract first days of the weeks from a Month from Unix timestamp

There is this Unix timestamp and it needs to generate the first days of the week as an array.

$time = '1456034400';
// This present Month February 2016
// in calendar the February has the start of the week
// Sunday 7
// Sunday 14
// Sunday 21
// Sunday 28


How do you get an array like this from the Unix Timestamp:

$weekdays = array(
0 => 7,
1 => 14,
2 => 21,
3 => 28
);


And this method needs to work and be accurate for any given month in years not just Feb 2016.

Answer
function getSundays($y, $m)
{
    return new DatePeriod(
        new DateTime("first Sunday of $y-$m"),
        DateInterval::createFromDateString('next sunday'),
        new DateTime("last day of $y-$m")
    );
}


$days="";
foreach (getSundays(2016, 04) as $Sunday) {
    $days[] = $Sunday->format("d");
}

var_dump($days);

https://3v4l.org/DVYM5