Chris
Chris

Reputation: 677

Get next monday date in PHP (including today)

I am creating a PHP page that based on a date, will get the date of the next Monday.

A snippet of my code is below - I am obtaining the next monday date using the DateTime and modify methods, but what I need to include is that if today's date is Monday, I want to select that (as it is only selecting the next monday, not including today.

$startDate = new DateTime();
$startDate->modify('next monday')->format('d-m-Y');

How can I change this so that if today is a Monday, it uses today's date and not the next Monday after it?

Upvotes: 2

Views: 611

Answers (2)

Chris
Chris

Reputation: 677

Thank you all for the posts, I chose to take the approach of getting the number of the day using $day = $startDate->format('N'); and then creating an if statement to check if the number equals 1.

Upvotes: 0

Xenofexs
Xenofexs

Reputation: 511

With date(); you can get the number of the day (ex : 1 for monday) and you can use mktime for specifie a timestamp

Example for get the number of the current day :

echo date('N'); // show : 5 cause we are Friday when you post your question

Example (from the doc) for date + mktime :

// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

So, you can do something like that :

// Cause we are the 08/04/2016, this line print 6 (cause tomorow is the 6th day of the week) 
echo date("N", mktime(0, 0, 0, date('m'), date(d)+1, date('Y')));

If you can get the number of the current day, you can (with a little mathematics) find the next monday.

Use/handle/train this functions and come back if you need more help :).

Upvotes: 1

Related Questions