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

后端 未结 28 1476
孤城傲影
孤城傲影 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 09:02

    Using Zend_Date it's pretty easy:

    $date->setDay($date->get(Zend_Date::MONTH_DAYS));
    
    0 讨论(0)
  • 2020-11-22 09:04

    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

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

    There is also the built in PHP function cal_days_in_month()?

    "This function will return the number of days in the month of year for the specified calendar." http://php.net/manual/en/function.cal-days-in-month.

    echo cal_days_in_month(CAL_GREGORIAN, 11, 2009); 
    // = 30
    
    0 讨论(0)
  • 2020-11-22 09:07

    I have wrapped it in my date time helper class here https://github.com/normandqq/Date-Time-Helper using $dateLastDay = Model_DTHpr::getLastDayOfTheMonth();

    And it is done

    0 讨论(0)
  • 2020-11-22 09:07
        $startDate = '2011-12-01';
        $endDate = date('Y-m');
        while (true) {
            try {
                $startDateTime = new DateTime($startDate);
                $startDateTime->add(new DateInterval('P1M'));
                $startDate = $startDateTime->format('Y-m-d');
                $endTime = $startDateTime->format('Y-m-t');
                echo $startDate . ' => ' . $endTime . PHP_EOL;
                if ($startDateTime->format('Y-m') == $endDate) {
                    break;
                }
            } catch (Exception $exception) {
                var_dump($exception->getMessage());
                break;
            }
        }
    

    After testing many solutions, this works best for me.

    0 讨论(0)
  • 2020-11-22 09:08
    $date1 = $year.'-'.$month; 
    $d = date_create_from_format('Y-m',$date1); 
    $last_day = date_format($d, 't');
    
    0 讨论(0)
提交回复
热议问题