php DateTime类和上个月

sgtfey8w  于 2022-12-10  发布在  PHP
关注(0)|答案(3)|浏览(189)

我对DateTime类有一些奇怪的行为。
今天是2012-05-31。时区是“欧洲/维尔纽斯”。
以下代码

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

输出2012-05-01。这是一个php bug吗?顺便说一下,$date = new DateTime('-1 month');的输出是一样的。

bxjv4tth

bxjv4tth1#

This seems to be special case for months with 31 days:
Note that '-1 month' may produce unexpected result when used in last day of month that has 31 days (from http://www.php.net/manual/de/datetime.formats.relative.php#102947)
What you can do is:

$date = new DateTime('last day of last month'); // this is "2012-04-30" now
/// 'first day of last month' would work either, of course

And then it depends on what you are going to do with the date.

6qfn3psc

6qfn3psc2#

我认为您需要有一个已经存在的日期时间并修改它,如下所示:

<?php
$d = new DateTime( date("Y-m-d") );
$d->modify( 'last day of previous month' );
echo $d->format( 'Y-m-d' ), "\n";
?>
n53p2ov0

n53p2ov03#

这是一个代码块,我希望它能有所帮助:
今天注意的是:2022-12-05

const MONTH_YEAR_DAY_FORMAT = 'Y-m-d';

 
    $startDate_m = new \DateTimeImmutable("first day of this month");
    $endDate_m = new \DateTimeImmutable("last day");
    $startDate_m_1 = new \DateTimeImmutable("first day of previous month");
    $endDate_m_1 = $endDate_m->modify("-1 month");

    echo  $startDate_m->format(self::MONTH_YEAR_DAY_FORMAT);
    echo  $endDate_m ->format(self::MONTH_YEAR_DAY_FORMAT);
    echo  $startDate_m_1 ->format(self::MONTH_YEAR_DAY_FORMAT);
    echo  $endDate_m_1 ->format(self::MONTH_YEAR_DAY_FORMAT);

// result
// startDate_m:   2022-12-01 
// endDate_m:     2022-12-05 
// startDate_m_1: 2022-11-01 
// endDate_m_1:   2022-12-05

相关问题