1

Given just the name of a day of the week (Monday, Tuesday...Sunday), how can I find the date of the next occurrence of that day?

I want to be able to press a button and then get a list of dates for each day of the week, for the following week. My weeks will run Monday to Sunday. So for example, on Friday I want to click it and get the dates for the coming Monday to Sunday. On a Monday I want to click it and get the dates for the following Monday to Sunday.

Hope this makes sense.

1

4 Answers 4

3

I always prefer the Object Oriented way using DateTime

// Create a new DateTime object
$date = new DateTime();

// Modify the date it contains
$date->modify('next monday');

// Output
echo $date->format('Y-m-d');

The nice thing is that you can also do this with dates other than today:

// Create a new DateTime object
$date = new DateTime('2006-05-20');

// Modify the date it contains
$date->modify('next monday');

// Output
echo $date->format('Y-m-d');

And even better, and to answer your second question (I didn't know this until today) :

$monday = new DateTime('monday');

// clone start date
$endDate = clone $monday;

// Add 7 days to start date
$endDate->modify('+7 days');

// Increase with an interval of one day
$dateInterval = new DateInterval('P1D');

$dateRange = new DatePeriod($monday, $dateInterval, $endDate);

foreach ($dateRange as $day) {
    echo $day->format('Y-m-d')."<br />";
}

References

PHP Manual - DateTime

PHP Manual - DateInterval

PHP Manual - DatePeriod

PHP Manual - clone

2

Your first question has a very simple answer, strtotime has that (and a lot more) functionality:

$timestamp = strtotime("next Wednesday");

gives you the timestamp (midnight) of the next given weekday (if today is wednesday it would give the NEXT wedensday)

To get the list you mention in the second part of you question, just loop through all the weekdays run the this code.

In case you dont know the $timestamp can be easily converet to a readable date with strftime().

For any advanced date-logic please also check out the documentation of the powerful DateTime-class.

1
$date = strtotime("next monday");

$date_str = date("Y-m-d", $date);

echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";

http://php.net/manual/en/function.strtotime.php

1
strtotime("next $day_of_week");

Not the answer you're looking for? Browse other questions tagged or ask your own question.