php得到给定月份的最后一天

问题描述 投票:9回答:4

我想输出当年特定月份的最后和第一个日期。我正在使用此代码但不起作用

$month='02';
$first_day_this_month = date('Y-'.$month.'-01'); // hard-coded '01' for first day
$last_day_this_month  = date('Y-'.$month.'-t');

echo $first_day_this_month;print'<->';echo $last_day_this_month;

我的输出显示

2015-02-01<->2015-02-31

但它将是2015-02-01<->2015-02-28

php date datetime
4个回答
14
投票

我之前遇到过PHP的这个问题,请尝试以下方法:

$dateToTest = "2015-02-01";
$lastday = date('t',strtotime($dateToTest));

4
投票

有很多方法可以做到这一点,我给你两个答案\想法:

1-尝试使用strtotime PHP函数(http://php.net/manual/es/function.strtotime.php

date("Y-m-d", strtotime("last day of this month"));或第一天......或任何月份。

2-其他方式你可以使用它:

第一天:

date("Y-m-d", mktime(0, 0, 0, *YOUR MONTH PARAM*,1 ,date("Y")));

最后一天:

date("Y-m-d", mktime(0, 0, 0, *YOUR MONTH PARAM*+1,0,date("Y")));

在这里阅读mktime函数:

http://php.net/manual/es/function.mktime.php

祝好运!


2
投票

你可以使用DateTime类。

    $month='02';
    $first_day_this_month = date('Y-'.$month.'-01');

    $firstDayThisMonth = new \DateTime($first_day_this_month);

    $lastDayThisMonth = new \DateTime($firstDayThisMonth->format('Y-m-t'));
    $lastDayThisMonth->setTime(23, 59, 59);

    echo $firstDayThisMonth->format("Y-m-d");
    echo "<->";
    echo $lastDayThisMonth->format("Y-m-d");

0
投票

您可以使用DateTime方法:

$month = '02';

$date = new DateTime(date('Y').'-'.$month.'-01');
$date->modify('first day of this month');
$first_day_this_month = $date->format('Y-m-d');

$date->modify('last day of this month');
$last_day_this_month = $date->format('Y-m-d');
© www.soinside.com 2019 - 2024. All rights reserved.