How to find the last day of the month from date?

2018-12-31 15:24发布

How can I get the last day of the month in PHP?

Given:

$a_date = "2009-11-23"

I want 2009-11-30; and given

$a_date = "2009-12-23"

I want 2009-12-31.

标签: php date
23条回答
梦该遗忘
2楼-- · 2018-12-31 15:54

Here is a complete function:

public function get_number_of_days_in_month($month, $year) {
    // Using first day of the month, it doesn't really matter
    $date = $year."-".$month."-1";
    return date("t", strtotime($date));
}

This would output following:

echo get_number_of_days_in_month(2,2014);

Output: 28

查看更多
墨雨无痕
3楼-- · 2018-12-31 15:55

The code using strtotime() will fail after year 2038. (as given in the first answer in this thread) For example try using the following:

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

It will give answer as: 1970-01-31

So instead of strtotime, DateTime function should be used. Following code will work without Year 2038 problem:

$d = new DateTime( '2040-11-23' ); 
echo $d->format( 'Y-m-t' );
查看更多
与风俱净
4楼-- · 2018-12-31 15:56

If you use the Carbon API extension for PHP DateTime, you can get the last day of the month with:

$date = Carbon::now();
$date->addMonth();
$date->day = 0;
echo $date->toDateString(); // use toDateTimeString() to get date and time 
查看更多
裙下三千臣
5楼-- · 2018-12-31 15:57

You can find last day of the month several ways. But simply you can do this using PHP strtotime() and date() function.I'd imagine your final code would look something like this:

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

Live Demo

But If you are using PHP >= 5.2 I strongly suggest you use the new DateTime object. For example like below:

$a_date = "2009-11-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');

Live Demo

Also, you can solve this using your own function like below:

/**
 * 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);
查看更多
情到深处是孤独
6楼-- · 2018-12-31 15:59

I know this is a little bit late but i think there is a more elegant way of doing this with PHP 5.3+ by using the DateTime class :

$date = new DateTime('now');
$date->modify('last day of this month');
echo $date->format('Y-m-d');
查看更多
回忆,回不去的记忆
7楼-- · 2018-12-31 15:59

You can also use it with datetime

$date = new \DateTime();
$nbrDay = $date->format('t');
$lastDay = $date->format('Y-m-t');
查看更多
登录 后发表回答