John Brunner John Brunner - 1 year ago 126
PHP Question

Get dates from next week in PHP

I want to

the dates from Mo,Tu,We,Th,Fr,Sa,Su of the next week.

My code looks like this at the moment:

$date_monday = date("Y-m-d", strtotime('next monday'));
$date_tuesday = date("Y-m-d", strtotime('next tuesday'));
$date_wednesday = date("Y-m-d", strtotime('next wednesday'));
$date_thursday = date("Y-m-d", strtotime('next thursday'));
$date_friday = date("Y-m-d", strtotime('next friday'));
$date_saturday = date("Y-m-d", strtotime('next saturday'));
$date_sunday = date("Y-m-d", strtotime('next sunday'));

Problem is that for example the date of
is wrong, because the next sunday is tomorrow, but I want the date from the sunday of the following week.

Is there a way to set the PHP date to sunday and calculate the days with the new date?

Answer Source

This can easily be achieved via DateTime class:

$dt = new DateTime();
// create DateTime object with current time

$dt->setISODate($dt->format('o'), $dt->format('W') + 1);
// set object to Monday on next week

$periods = new DatePeriod($dt, new DateInterval('P1D'), 6);
// get all 1day periods from Monday to +6 days

$days = iterator_to_array($periods);
// convert DatePeriod object to array

// $days[0] is Monday, ..., $days[6] is Sunday
// to format selected date do: $days[1]->format('Y-m-d');


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download