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

How can I calculate the day of the month in PHP by specifying the month, year, day of the week and number of weeks.
For example, if I have September 2013 and the day of the week is Friday, and the number of weeks is 2, I should get 6. (9/6/2013 - Friday on the 2nd week.)

+4
source share
3 answers

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

Unfortunately, this is not so simple:

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

For weeks to work as you like, 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('Ym-d', $second_week_friday); // 2013-09-13 

Note Starting from the first day of the month, starting from the first week, I reduced this week accordingly.

+4
source

I was going to suggest just strtotime() like this:

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

It doesn't seem like the way you want the calendar to behave? But it follows the (correct) standard :)

+3
source

So it is 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" 
0
source

Source: https://habr.com/ru/post/1501493/


All Articles