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

后端 未结 28 1452
孤城傲影
孤城傲影 2020-11-22 08:56

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_dat         


        
相关标签:
28条回答
  • 2020-11-22 08:57

    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');
    
    0 讨论(0)
  • 2020-11-22 08:59

    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));
    
    0 讨论(0)
  • 2020-11-22 08:59

    Your solution is here..

    $lastday = date('t',strtotime('today'));
    
    0 讨论(0)
  • 2020-11-22 08:59
    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

    0 讨论(0)
  • 2020-11-22 09:00

    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

    0 讨论(0)
  • 2020-11-22 09:02

    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' );
    
    0 讨论(0)
提交回复
热议问题