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 16:06
function first_last_day($string, $first_last, $format) {
    $result = strtotime($string);
    $year = date('Y',$result);
    $month = date('m',$result);
    $result = strtotime("{$year}-{$month}-01");
    if ($first_last == 'last'){$result = strtotime('-1 second', strtotime('+1 month', $result)); }
    if ($format == 'unix'){return $result; }
    if ($format == 'standard'){return date('Y-m-d', $result); }
}

http://zkinformer.com/?p=134

查看更多
余欢
3楼-- · 2018-12-31 16:07

t returns the number of days in the month of a given date (see the docs for date):

$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));
查看更多
笑指拈花
4楼-- · 2018-12-31 16:07

There are ways to get last day of month.

//to get last day of current month
echo date("t", strtotime('now'));

//to get last day from specific date
$date = "2014-07-24";
echo date("t", strtotime($date));

//to get last day from specific date by calendar
$date = "2014-07-24";
$dateArr=explode('-',$date);
echo cal_days_in_month(CAL_GREGORIAN, $dateArr[1], $dateArr[0]); 
查看更多
余生无你
5楼-- · 2018-12-31 16:10

Carbon API extension for PHP DateTime

Carbon::parse("2009-11-23")->lastOfMonth()->day;

or

Carbon::createFromDate(2009, 11, 23)->lastOfMonth()->day;

will retrun

30
查看更多
心情的温度
6楼-- · 2018-12-31 16:11

An other way using mktime and not date('t') :

$dateStart= date("Y-m-d", mktime(0, 0, 0, 10, 1, 2016)); //2016-10-01
$dateEnd = date("Y-m-d", mktime(0, 0, 0, 11, 0, 2016)); //This will return the last day of october, 2016-10-31 :)

So this way it calculates either if it is 31,30 or 29

查看更多
临风纵饮
7楼-- · 2018-12-31 16:13

Using Zend_Date it's pretty easy:

$date->setDay($date->get(Zend_Date::MONTH_DAYS));
查看更多
登录 后发表回答