发现日期是否在一个月的最后一周


PHP: Discover if day resides in the last week of the month

客户希望每周一自动生成一份时事通讯,显示下一周的日程安排。这很简单:

if(date('N', $time)==1) { /* Stuff */ }

将它附加到每晚运行的crontab上,我就可以开始了。

但是,如果时事通讯是在一个月的最后一周生成的,它需要显示下一个月的日程安排。如何确定何时需要生成月度计划?

date('m') == date('m', strtotime('+1 week'))

如果从报表运行日期起一周后的月份与当前月份不同,则显示报表!

if(date('n', $time) !== date('n', $time+518400)){
    // Six days from now it will be a new month
}

一种方法可能是看看下周一是否在不同的月份。

if (date('n', $time) != date('n', $time + 7*24*60*60)) { ... }

您可以更花哨,但这似乎与您现有的代码一致。

您可以使用t日期格式参数查看特定月份中有多少天。试着

if ((date('t', $time) - date('j', $time)) > 6) {
    // in the last week of the month
}

我知道这是一个答案,但这将有助于更多:

PHP的内置时间函数使这更加简单。http://php.net/manual/en/function.strtotime.php

// Get first Friday of next month.
$timestamp = strtotime('first fri of next month');
// Get second to last Friday of the current month.
$timestamp = strtotime('last fri of this month -7 days');
// Format a timestamp as a human-meaningful string.
$formattedDate = date('F j, Y', strtotime('first wed of last month'));