ChatGPT解决这个技术问题 Extra ChatGPT

如何从日期找到一个月的最后一天?

如何在 PHP 中获取一个月的最后一天?

鉴于:

$a_date = "2009-11-23"

我要2009-11-30;并给出

$a_date = "2009-12-23"

我想要 2009 年 12 月 31 日。


S
SilentGhost

t 返回给定日期当月的天数(参见 the docs for date):

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

这将在 2038 年后失败。因此,应该使用 DateTime 函数而不是 strtotime。以下代码将在没有 2038 年问题的情况下工作: $d = new DateTime( '2009-11-23' ); echo $d->format('Ymt');
@Mugunth 如果您使用 24 年后的日期,您可能会在 2038 年之前遇到问题,但是,服务器已经转向 64 位架构,这将为我们提供大约 2920 亿年的时间来解决问题。
在程序中 -> $date1 = $year.'-'.$month; $d = date_create_from_format('Ym',$date1); $last_day = date_format($d, 't');
使用 DateTime,您可以执行以下操作:(new DateTime('2009-11-23'))->modify('last day of')
@victor,您应该将您的评论作为答案,唯一的原因是它会产生可读和可理解的代码。显然使用 Ymt 也可以,但是谁不看文档就会知道“t”是什么?
M
Mugunth

使用 strtotime() 的代码将在 2038 年后失败。(如本线程的第一个答案所示)例如尝试使用以下内容:

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

它将给出答案:1970-01-31

所以应该使用 DateTime 函数而不是 strtotime。以下代码将在没有 2038 年问题的情况下工作:

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

我将 71 岁退休,所以对我来说不是问题! j/k 但说真的,伙计们——注意这个警告!
这假设您正在运行 32 位版本的 PHP。
为什么 php 文档 php.net/manual/de/function.strtotime.php 中没有提到 strtotime 这个令人震惊的事实?
@Adam现在是,不确定您是否在检查时。 php.net/manual/de/…
截至 2018 年,strtotime 代码为我提供了以下结果:2040-11-30
H
Hannoun Yassir

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

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

在一行中: $date = new DateTime('本月的最后一天');
您可能要添加 $date->modify('本月的最后一天')->setTime(23,59,59);如果您想使用此 dateTime 来比较时间很重要的地方。 (这给了你本月的最后一秒)
这有效:$date = new DateTime('last day of 2020-2');
@约翰你错了。最后一天是使用 $date 对象而不是系统日期计算的。通过更改第一行来尝试:$date = DateTime::createFromFormat('m/d/Y', '1/10/2014');
如果您想或至少尝试我要求您做的事情,您会看到 this month 表示 DateTime 对象中月份的值,而不是系统的日期。如果您无法键入/运行 php 代码,这可能会有所帮助:sandbox.onlinephpfunctions.com/code/…
M
MPV

还有内置的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

这个答案比使用 strtoTime 简单和恰当得多。我没有看到任何缺点。到顶部你去。
k
kaleazy

这应该有效:

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

j
john Smith

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

我想知道我没有看到 DateTime::createFromFormat,单行

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

我同意。这个解决方案(DateTime 类)比使用旧的 datetime 函数要好得多。
M
Mohammed Safeer

试试这个,如果你使用的是 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');

等等..


这是正确的答案。为了补充您的答案,您也可以像这样使用它$date = new DateTime('last day of 2022-06');
n
nikc.org

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


使用相同方法的另一种方法是将 mktime 指定为下个月的第 0 天 mktime(0, 0, 0, $month+1, 0, $year);
对我而言,不鼓励使用 strtotime()mktime()。已知的错误,如月份边缘的日期确定和闰年计算。由于 DateTime 可用,您应该使用此类以避免将来出现任何问题。就像我之前多次说过的那样,这两个函数 strtotime()mktime() 都将在 2038 年之后失败。这就是我投反对票的原因......
@PaulT.Rawkeen 这个答案已经超过 4 年了。与互联网上的任何东西一样,在衡量相关性和有用性时,年龄应该是一个因素。此外,恕我直言,与技术相关的任何事情的减半时间都特别短。
@nikc.org 我同意,尤其是关于所有技术解决方案和解决问题的方法的生命周期。在这种特殊情况下,答案的赞成票数量相对较多,并且可能有人(初级程序员)会将此答案视为可接受的解决方案。它简短而优雅:),他可能会得到预期的结果,但随着时间的推移,这种解决此类问题的方法变得棘手,我们应该在可能的情况下警告这些事实。亲切的问候。
F
Faisal

您可以通过多种方式找到该月的最后一天。但是您可以简单地使用 PHP strtotime()date() 函数来执行此操作。我想您的最终代码将如下所示:

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

Live Demo

但是如果您使用的是 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');

Live Demo

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

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

仅供参考,现场演示链接不再起作用。
b
bensiu

你的解决方案在这里..

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

这为 September 提供了 31,如您所知,这是不正确的。
M
Max

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

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

从另一个 DateTime 对象

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

e
eaykin

如果您使用 PHP DateTime 的 Carbon API 扩展,您可以通过以下方式获取该月的最后一天:

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

实际上,如果您将 day 设置为 -1,它将得到最后一个。因此,您必须将 day 设置为 0 才能获得最后一天。 $date->day = 0;
谢谢@GiovanneAfonso,这是正确的。我将日期设置为 0 并测试了答案。
如果您使用的是 Carbon,一种单行方法是使用:Carbon::Now()->endOfMonth()。但是,endOfMonth() 是一个修饰符,因此如果您有一个现有变量保存碳日期(或日期将被修改),请使用“克隆”。
A
Ajouve

您也可以将它与日期时间一起使用

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

C
Christian Lescuyer

Carbon PHP DateTime 的 API 扩展

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

或者

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

将返回

30

感谢您推荐 Carbon 库。
k
kayla
$date1 = $year.'-'.$month; 
$d = date_create_from_format('Y-m',$date1); 
$last_day = date_format($d, 't');

K
Kaushik shrimali

如果你有一个月明智的得到这个月的最后一天,那么,

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

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

j
justnajm

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

m
mkerstner

使用 Zend_Date 非常简单:

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

R
Robin Rumeau

使用 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


u
user2448808

我将 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'));

F
Firze

这是一个完整的功能:

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


v
vineet

有几种方法可以获得一个月的最后一天。

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

J
JSG

我迟到了,但是如上所述,有一些简单的方法可以做到这一点:

$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() 可以完全控制时间的各个方面... IE

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

将日期设置为 0 并将您的月份上移 1 将为您提供上个月的最后一天。 0 和负数在不同的论点中具有相似的影响。 PHP: mktime - Manual

正如一些人所说,strtotime 不是最可靠的方法,而且几乎没有那么容易通用。


c
codediesel

如果你想回去几个月,你也可以做这样的事情。

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

N
Norman

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

它完成了


W
Winn Minn Soe
    $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;
        }
    }

在测试了许多解决方案之后,这对我来说效果最好。


k
kaiser
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


Z
ZPKSoft Paweł Krzyżanowski

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

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

L
Louis Sterio

这是获得月底的一种更优雅的方式:

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

S
SilentGhost

您可以在日期函数中使用“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";

代码是不言自明的。所以希望它有所帮助。