PHP如何中获取本月的最后一天

时间:2017-07-28
本文章向大家介绍php如何获取某一月份的最后一天,有几种方法可以实现,需要的朋友可以参考一下。

如何在PHP中获取本月的最后一天?

例如:

$a_date = "2009-11-23"

我想要获得2009-11-30;

再例如,给定

$a_date = "2009-12-23"

我想获得2009-12-31。

第一种实现方法:返回给定日期月份的天数

$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));

 t返回给定日期月份的天数。

第二种方法:

使用strtotime()的代码将在2038年之后失败。(如此线程中的第一个答案所示)例如,尝试使用以下代码:

$a_date = "2040-11-23";
echo date("Y-m-t", strtotime($a_date));

它将给出答案:1970-01-31

因此,应该使用DateTime函数而不是strtotime。以下代码将在没有2038年问题的情况下工作:

$d = new DateTime( '2040-11-23' ); 
echo $d->format( 'Y-m-t' );

第三种方法:cal_days_in_month()

PHP函数cal_days_in_month(),此函数将返回指定日历的一年中的天数。

echo cal_days_in_month(CAL_GREGORIAN, 11, 2009); 

第四种方法:

此外,您可以使用自己的功能解决此问题,如下所示:

/**
 * Last date of a month of a year
 *
 * @param[in] $date - Integer. Default = Current Month
 *
 * @return Last date of the month and year in yyyy-mm-dd format
 */
function last_day_of_the_month($date = '')
{
    $month  = date('m', strtotime($date));
    $year   = date('Y', strtotime($date));
    $result = strtotime("{$year}-{$month}-01");
    $result = strtotime('-1 second', strtotime('+1 month', $result));

    return date('Y-m-d', $result);
}

$a_date = "2009-11-23";
echo last_day_of_the_month($a_date);