Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get dates from next week in PHP

I want to echo 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 sunday 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?

like image 414
John Brunner Avatar asked Nov 23 '13 12:11

John Brunner


People also ask

How can I get next Monday date in PHP?

echo(strtotime("+1 week 3 days 7 hours 5 seconds") . "<br>"); echo(strtotime("next Monday") . "<br>");

How can I get tomorrow day in PHP?

$d=strtotime("tomorrow");

How do I get the start of the week in PHP?

Use strtotime() function to get the first day of week using PHP. This function returns the default time variable timestamp and then use date() function to convert timestamp date into understandable date.

What is strtotime function in PHP?

The strtotime() function is a built-in function in PHP which is used to convert an English textual date-time description to a UNIX timestamp. The function accepts a string parameter in English which represents the description of date-time. For e.g., “now” refers to the current date in English date-time description.


1 Answers

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

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

Demo

like image 168
Glavić Avatar answered Oct 13 '22 23:10

Glavić