如何创建一个函数,可以找出上个月的最后一天的日期? [英] How can I create a function that can figure out the previous month's last day dates?

查看:728
本文介绍了如何创建一个函数,可以找出上个月的最后一天的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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语句,检查数字是否大于当前月份的总天数,如果是,则减去

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天。此外,2月和闰年是一个问题。有没有人知道一个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.

这篇关于如何创建一个函数,可以找出上个月的最后一天的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆