Calculate day of month with month, year, day of week and number of week

妖精的绣舞 提交于 2021-02-07 16:41:47

问题


How can I calculate the day of month in PHP with giving month, year, day of week and number of week.
Like, if I have September 2013 and day of week is Friday and number of week is 2, I should get 6. (9/6/2013 is Friday on the 2nd week.)


回答1:


One way to achieve this is using relative formats for strtotime().

Unfortunately, it's not as straightforward as:

strtotime('Friday of second week of September 2013');

In order for the weeks to work as you mentioned, you need to call strtotime() again with a relative timestamp.

$first_of_month_timestamp = strtotime('first day of September 2013');
$second_week_friday = strtotime('+1 week, Friday', $first_of_month_timestamp);
echo date('Y-m-d', $second_week_friday); // 2013-09-13

Note: Since the first day of the month starts on week one, I've decremented the week accordingly.




回答2:


I was going to suggest to just use strtotime() in this fashion:

$ts = strtotime('2nd friday of september 2013');
echo date('Y-m-d', $ts), PHP_EOL;
// outputs: 2013-09-13

It seems that this is not how you want the calendar to behave? But it is following a (proper) standard :)




回答3:


This way its a little longer and obvious but it works.

/* INPUT */
$month = "September";
$year = "2013";
$dayWeek= "Friday";
$week = 2;

$start = strtotime("{$year}/{$month}/1"); //get first day of that month
$result = false;
while(true) { //loop all days of month to find expected day
    if(date("w", $start) == $week && date("l", $start) == $dayWeek) {
        $result = date("d", $start);
        break;
    }
    $start += 60 * 60 * 24;
}

var_dump($result); // string(2) "06"


来源:https://stackoverflow.com/questions/18721598/calculate-day-of-month-with-month-year-day-of-week-and-number-of-week

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!