【问题标题】:get last day of the next month in php?在php中获取下个月的最后一天?
【发布时间】:2020-03-31 15:51:21
【问题描述】:

我有一个如下所示的 php 代码,我试图在其中检索下个月的最后一天。

<?php

date_default_timezone_set('America/Toronto');

echo date('l jS \of F Y h:i:s A');

$next_month_last_day  = date('t', strtotime('next month'));  // last day of the next month

print_r("\n");

print_r($next_month_last_day);   // Line A

?>

问题陈述:

我想知道我在上面的 php 代码中犯了什么错误,因为 A 行 处的代码打印 31。它应该打印 30,因为最后一个 下个月(四月)是 30 号。

【问题讨论】:

标签: php date


【解决方案1】:

随便用

date('d', strtotime('last day of +1 month'));

【讨论】:

    【解决方案2】:

    您可以使用last day of next month

    $date = new \DateTime('last day of next month');
    echo $date->format('Y-m-d');
    

    【讨论】:

      【解决方案3】:

      另一种方法是获取下个月的第一天,然后使用t 将其格式化为该月的天数。

      echo date("t", strtotime("first day of next month")); // 2021-04-30  10:27:35
      

      【讨论】:

        【解决方案4】:

        我必须手动覆盖今天的日期,这样 DateTime 就不会跳过一个月。但这没关系,因为您只想知道下个月是什么。

        $dateTime = new DateTime('now', new DateTimeZone("America/Toronto"));
        $dateTime->setDate($dateTime->format('Y'), $dateTime->format('m'), 01);
        
        $nextMonth = $dateTime->modify('+1 month');
        
        echo cal_days_in_month(CAL_GREGORIAN, $nextMonth->format('m'), $nextMonth->format('Y'));
        

        【讨论】:

          【解决方案5】:

          试试这个

          $lastDay = date('t',strtotime('next month'));
          
           
          
          print_r($lastDay);
          

          【讨论】:

            猜你喜欢
            • 2012-11-29
            • 1970-01-01
            • 1970-01-01
            • 2021-07-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多