Pringles
Pringles

Reputation: 4615

PHP: get weekday number of the month

I'm looking for functionality that would do the opposite of

strtotime("third monday");

i.e. a function that is fed a timestamp and would return the weekday number of the month.

So if today is 18.07.2016, ideally the function should return "3" (i.e. 3rd Monday of July).

I can get the weekday itself by using date("D", [timestamp]), but I'm not sure how to calculate that it is in fact the third one this month.

Has anyone tried doing anything like this before?

Upvotes: 3

Views: 1660

Answers (2)

mister martin
mister martin

Reputation: 6252

You'll want to verify you're working within a valid date range, but this is a relatively simple task:

$today = date('d', time());
echo 1 + floor(($today - 1) / 7); // nth day of month

Upvotes: 2

Stephen Fox
Stephen Fox

Reputation: 87

You should look into the Carbon class. It expands date and time functions to basically everything you'd ever need, including human-readable timestamps (ie. "5 minutes ago")

These two would be useful to you - the day and week of the month.

var_dump($dt->dayOfWeek);                                    // int(3)

var_dump($dt->weekOfMonth);                                  // int(1)

http://carbon.nesbot.com/docs/#api-getters

Upvotes: 1

Related Questions