简体   繁体   中英

PHP: get weekday number of the month

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

strtotime("third monday");

ie 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" (ie 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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM