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

后端 未结 28 1478
孤城傲影
孤城傲影 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:08

    If you have a month wise get the last date of the month then,

    public function getLastDateOfMonth($month)
        {
            $date = date('Y').'-'.$month.'-01';  //make date of month 
            return date('t', strtotime($date)); 
        }
    
    $this->getLastDateOfMonth(01); //31
    
    0 讨论(0)
  • 2020-11-22 09:09

    Carbon API extension for PHP DateTime

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

    or

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

    will return

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

    This a much more elegant way to get the end of the month:

      $thedate = Date('m/d/Y'); 
      $lastDayOfMOnth = date('d', mktime(0,0,0, date('m', strtotime($thedate))+1, 0, date('Y', strtotime($thedate)))); 
    
    0 讨论(0)
  • 2020-11-22 09:13

    This should work:

    $week_start = strtotime('last Sunday', time());
    $week_end = strtotime('next Sunday', time());
    
    $month_start = strtotime('first day of this month', time());
    $month_end = strtotime('last day of this month', time());
    
    $year_start = strtotime('first day of January', time());
    $year_end = strtotime('last day of December', time());
    
    echo date('D, M jS Y', $week_start).'<br/>';
    echo date('D, M jS Y', $week_end).'<br/>';
    
    echo date('D, M jS Y', $month_start).'<br/>';
    echo date('D, M jS Y', $month_end).'<br/>';
    
    echo date('D, M jS Y', $year_start).'<br/>';
    echo date('D, M jS Y', $year_end).'<br/>';
    
    0 讨论(0)
  • 2020-11-22 09:13

    I needed the last day of the next month, maybe someone will need it:

    echo date("Y-m-t", strtotime("next month")); //is 2020-08-13, return 2020-09-30
    
    0 讨论(0)
  • 2020-11-22 09:14

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