根据实际年份的周+月生成新日期

时间:2019-04-08 12:41:22

标签: php

我正在开发具有固定间隔的日历。 但是在年中和年末有2个假期。 年中假期从该年的7月星期一的3°开始, 年底假期从该年的12月倒数第二个星期一开始。

有什么办法可以获取或生成这个休假日期?

我找到的最接近的东西是这样的

$mid_vacation= date('w',strtotime($my_date.'Monday last week'));

2 个答案:

答案 0 :(得分:2)

There may be more ways, but the terms to follow all work as desired. I don't find instantiating a date class object to be as attractive because you don't need any of the extra functionality after generating the string. For this reason, I recommend strtotime() with date(). You are free to select which ever expression you wish depending on "readability", "brevity", or whatever criteria.

Code: (Demo)

echo "3rd Monday of July: " , date("Y-m-d", strtotime("first Monday of July +2 weeks"));
echo "\n";
echo "3rd Monday of July: " , date("Y-m-d", strtotime("+2 weeks first Monday of July"));
echo "\n";
echo "3rd Monday of July: " , date("Y-m-d", strtotime("third Monday of July"));

echo "\n---\n";

echo "Penultimate / Second last Monday in December: " , date("Y-m-d", strtotime("last Monday of December this year -1 week"));
echo "\n";
echo "Penultimate / Second last Monday in December: " , date("Y-m-d", strtotime("-1 week last Monday of December"));

Output:

3rd Monday of July: 2019-07-15
3rd Monday of July: 2019-07-15
3rd Monday of July: 2019-07-15
---
Penultimate / Second last Monday in December: 2019-12-23
Penultimate / Second last Monday in December: 2019-12-23

*December seems to require this year in the first expression; @fyrye tells us why...

The issue with December is due to the usage of last|first dayname of when using + or - since it assumes you are specifying a timezone. See the notes on Relative statements are always processed after non-relative statements. You can use -7 days last Monday of December instead https://3v4l.org/KBrEs0
fyrye

答案 1 :(得分:-1)

Check DateTime class

https://www.php.net/manual/en/class.datetime.php

$test = new DateTime('2019-07-01');
echo $test->modify('first monday')->format('Y-m-d');

$test = new DateTime('2019-12-01');
echo $test->modify('last monday of this month')->format('Y-m-d');