如何创建一个可以计算上一个月最后一天日期的功能?

问题描述:

我有一个PHP日历列出了一个月中的所有日子。在本月的第一天之前,我有上个月的数字,而在这个月的最后一天之后是下个月的数字。

I have a PHP calendar that lists all of the days of the month in a table. Before the first day of the month I have numbers from the prior month and after the last day of the month are the numbers of the days for the upcoming month.

以下是当前的日历照片。正如你可以看到底部的灰色数字是正常的,但是在月的第一天之前的数字是负数,应该显示为'29,30'

Here's a photo of the Calendar as it currently looks. As you can see the bottom gray numbers are working fine, but the numbers preceding the first day of the month are negative numbers and should instead appear as '29,30'

这个月的最后一天是例如32,33,34,所以我刚刚创建了一个if语句来检查数字是否大于当前月份的总天数,如果是,则减去总数例如,从32开始的月份天数,然后显示为1,2,3。

The numbers after the last day of the month were simply '32,33,34' for example, so I just created an if statement that checks if the number is greater than the total numbers of days in the current month and if so, then subtract the total numbers of days in the month from '32' for example, which would then make it appear as '1,2,3'.

if ($day > $total_days_of_current_month) {
  echo '<td>' . ($day - $total_days_of_current_month) . ' </td>'; // for example,33-31=2
}

我的问题是创建一个if声明,不知何故,知道上个月的最后几天是什么。问题是有几个月有30天,有的有31天。另外,二月和闰年也是一个问题。有谁知道一个if语句,所以我可以把它从上一个月看成是'28,29,30'?

My problem is creating an if statement that somehow knows what the last days of the prior month was. The problem is that some months have 30 days and some have 31 days. Also, the month of February and leap years are a problem. Does anyone know an if statement so i can make it appear as '28,29,30' from the previous month?

假设 $ day 是UNIX时间戳记:

Assuming $day is a UNIX timestamp:

// gets you the first of the month
$date = getdate(mktime(0, 0, 0, date('n', $day), 1, date('Y', $day)));

从这里,执行以下操作之一:

From here, do one of these:

$lastDayOfPrevMonth = strtotime('-1 day', $date[0]);

// or, better, get the first day "in the grid" (assuming week starts on Sunday)
$date = strtotime("-$date[wday] days", $date[0]);

我不想竖起它,但你看着我的以前的答案?这是构建日历而不是所有这种特殊情况检查的更强大的方法。

I don't want to harp on it, but have you looked at my previous answer? That's a more robust way to build a calendar instead of all this special case checking.