如何在PHP中获得每月的最后一天?

考虑到:

$a_date = "2009-11-23"

我想要2009-11-30;鉴于

$a_date = "2009-12-23"

我要2009-12-31。


T返回给定日期当月的天数(date参见文档):

$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));

你可以为下个月的第一天创建一个日期,然后使用strtotime("-1 day", $firstOfNextMonth)


您可以在日期函数中使用“t”来获得特定月份中的天数。

代码是这样的:

function lastDateOfMonth($Month, $Year=-1) {
    if ($Year < 0) $Year = 0+date("Y");
    $aMonth         = mktime(0, 0, 0, $Month, 1, $Year);
    $NumOfDay       = 0+date("t", $aMonth);
    $LastDayOfMonth = mktime(0, 0, 0, $Month, $NumOfDay, $Year);
    return $LastDayOfMonth;
}

for($Month = 1; $Month <= 12; $Month++)
    echo date("Y-n-j", lastDateOfMonth($Month))."\n";

代码是自解释的。希望这能有所帮助。


还有一个内置的PHP函数cal_days_in_month()?

"此函数将返回指定日历的某月中的天数。" http://php.net/manual/en/function.cal-days-in-month。

echo cal_days_in_month(CAL_GREGORIAN, 11, 2009); 
// = 30

如果您使用的是32位系统,那么由于2038年问题,strtotime()代码将在2038年之后失败。

例如,在32位系统上,此代码将回显1970-01-31:

$a_date = "2040-11-23";
echo date("Y-m-t", strtotime($a_date));

如果你需要你的代码支持32位系统,那么你应该使用DateTime函数:

$d = new DateTime('2040-11-23'); 
echo $d->format('Y-m-t');

该代码将在32位或64位系统上正确地输出2040-11-30。


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


你的解决方案在这里。

$lastday = date('t',strtotime('today'));

这应该可以工作:

$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/>';

您也可以将它与datetime一起使用

$date = new \DateTime();
$nbrDay = $date->format('t');
$lastDay = $date->format('Y-m-t');

$date1 = $year.'-'.$month; 
$d = date_create_from_format('Y-m',$date1); 
$last_day = date_format($d, 't');

我知道这有点晚了,但我认为有一种更优雅的方式来使用PHP 5.3+使用DateTime类:

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

我在这里将它包装在我的日期时间助手类中 https://github.com/normandqq/Date-Time-Helper 使用 $dateLastDay = Model_DTHpr::getLastDayOfTheMonth();

完成了


这是一个完整的函数:

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));
}

这将输出如下:

echo get_number_of_days_in_month(2,2014);

输出:28


有很多方法可以得到一个月的最后一天。

//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]); 

如果你使用碳API扩展PHP DateTime,你可以得到一个月的最后一天:

$date = Carbon::now();
$date->addMonth();
$date->day = 0;
echo $date->toDateString(); // use toDateTimeString() to get date and time 

试试这个,如果你使用的是PHP 5.3+,

$a_date = "2009-11-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');

为了查找下个月最后的日期,修改如下:

 $date->modify('last day of 1 month');
 echo $date->format('Y-m-d');

等等。


这是一个更优雅的表达月底的方式:

  $thedate = Date('m/d/Y'); 
  $lastDayOfMOnth = date('d', mktime(0,0,0, date('m', strtotime($thedate))+1, 0, date('Y', strtotime($thedate)))); 

使用Zend_Date非常简单:

$date->setDay($date->get(Zend_Date::MONTH_DAYS));

对我来说,最优雅的是使用DateTime

我不知道我没有看到DateTime::createFromFormat,一行程序

$lastDay = \DateTime::createFromFormat("Y-m-d", "2009-11-23")->format("Y-m-t");

另一种使用mktime而不是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 :)

所以用这种方法,它会计算它是31 30还是29


碳API扩展PHP DateTime

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

or

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

将返回

30

我迟到了,但有几个简单的方法可以做到这一点:

$days = date("t");
$days = cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y'));
$days = date("j",mktime (date("H"),date("i"),date("s"),(date("n")+1),0,date("Y")));

使用mktime()是我去完全控制时间的各个方面… 即

echo "<br> ".date("Y-n-j",mktime (date("H"),date("i"),date("s"),(11+1),0,2009));

将日期设置为0,将月份向上移动1,就会得到上个月的最后一天。0和负数在不同的参数中具有相似的影响。 PHP: mktime -手动

正如一些人说的,strtotime并不是最可靠的方法,而且很少有像strtotime这样容易通用的方法。


你可以用几种方法找到这个月的最后一天。但是,您可以简单地使用PHP strtotime()和date()函数来实现这一点。我认为你的最终代码应该是这样的:

$a_date = "2009-11-23";
echo date('Y-m-t',strtotime($a_date));

现场演示

但是如果你正在使用PHP >= 5.2,我强烈建议你使用新的DateTime对象。例如:

$a_date = "2009-11-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');

现场演示

此外,你可以使用自己的函数来解决这个问题,如下所示:

/**
 * Last date of a month of a year
 *
 * @param[in] $date - Integer. Default = Current Month
 *
 * @return Last date of the month and year in yyyy-mm-dd format
 */
function last_day_of_the_month($date = '')
{
    $month  = date('m', strtotime($date));
    $year   = date('Y', strtotime($date));
    $result = strtotime("{$year}-{$month}-01");
    $result = strtotime('-1 second', strtotime('+1 month', $result));

    return date('Y-m-d', $result);
}

$a_date = "2009-11-23";
echo last_day_of_the_month($a_date);

如果你知道一个月的最后一天,

public function getLastDateOfMonth($month)
    {
        $date = date('Y').'-'.$month.'-01';  //make date of month 
        return date('t', strtotime($date)); 
    }

$this->getLastDateOfMonth(01); //31

我使用strtotime与cal_days_in_month如下所示:

$date_at_last_of_month=date('Y-m-d', strtotime('2020-4-1
+'.(cal_days_in_month(CAL_GREGORIAN,4,2020)-1).' day'));

现在,如果你有月份和年份,DateTime可以很方便地做到这一点

$date = new DateTime('last day of '.$year.'-'.$month);

来自另一个DateTime对象

$date = new DateTime('last day of '.$otherdate->format('Y-m'));

    $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;
        }
    }

在测试了许多解决方案之后,这个方法最适合我。


我需要下个月的最后一天,也许有人会需要它:

echo date("Y-m-t", strtotime("next month")); //is 2020-08-13, return 2020-09-30

如果你想回到几个月前,你也可以这样做。

 $list = [
        0, 1, 2, 3
    ];

    $date = new \Datetime();
    $dates = [];
    foreach($list as $item)
    {

        $set = clone $date;
        $set->modify("-$item month ");
       $dates[] = $set->modify("last day of this month");
       
    }
    return $dates;

2行代码,你就完成了:

$oDate = new DateTime("2019-11-23");

// now your date object has been updated with last day of month    
$oDate->setDate($oDate->format("Y"),$oDate->format("m"),$oDate->format("t"));

// or to just echo you can skip the above line using this
echo $oDate->format("Y-m-t");