Php 如果月份有31天,则返回错误日期的strotime(';-1个月';)

Php 如果月份有31天,则返回错误日期的strotime(';-1个月';),php,date,datetime,Php,Date,Datetime,我正在尝试创建一个函数来返回前几个月的确切日期 这是我的代码示例: // Dates in TimeStamp $ts_now = strtotime('now'); $ts_month1 = strtotime("-1 month", $ts_now); $ts_month2 = strtotime("-2 month", $ts_now); $ts_month3 = strtotime("-3 month", $ts_now); // Dates Formated $date_now =

我正在尝试创建一个函数来返回前几个月的确切日期

这是我的代码示例:

// Dates in TimeStamp
$ts_now =  strtotime('now');
$ts_month1 = strtotime("-1 month", $ts_now);
$ts_month2 = strtotime("-2 month", $ts_now);
$ts_month3 = strtotime("-3 month", $ts_now);

// Dates Formated
$date_now = date('Y-m-d', $ts_now);
$date_month1 = date('Y-m-d', $ts_month1);
$date_month2 = date('Y-m-d', $ts_month2);
$date_month3 = date('Y-m-d', $ts_month3);

//Output
echo $date_now;    //2020-04-30
echo $date_month1; //2020-03-30
echo $date_month2; //2020-03-01
echo $date_month3; //2020-01-30
问题出现在代表2月的
$date\u month2
中,输出是2020-03-01,而不是2020-02-29,我认为问题将发生在有30天的月份,而当前日期为31天


解决这个问题的最佳方法是什么?

正如您所看到的,在月末工作可能会有问题,因为PHP是如何处理日期的。你最好的选择是回到月初,计算日期(即时间倒转),然后回到你想要的日期。这样,您可以检查当前日期是否大于月份的天数。如果是这样,请改用当月的最后一天

function getMonthsAgo(int $n): string {
    $date = new DateTime();
    $day  = $date->format('j');
    $date->modify('first day of this month')->modify('-' . $n . ' months');
    if ($day > $date->format('t')) {
        $day = $date->format('t');
    }
    $date->setDate($date->format('Y'), $date->format('m'), $day);
    return $date->format('Y-m-d');
}

// Dates Formated
$date_now = date('Y-m-d');
$date_month1 = getMonthsAgo(1);
$date_month2 = getMonthsAgo(2);
$date_month3 = getMonthsAgo(3);

//Output
echo $date_now;
echo $date_month1;
echo $date_month2;
echo $date_month3;
输出:

2020-04-30
2020-03-30
2020-02-29
2020-01-30

这一切都取决于你的预期结果。上个月的最后一天?30天前?28天?结果是动态的,我需要-x个月前的确切日期。如果今天是第31天,我需要20年3月30日或2020年2月29日。因此,您需要上个月的最后一天。我想我可以进行一些验证,并在我的项目中使用此代码。我工作了这么久,想不出这么简单的解决办法。谢谢你,伙计,很抱歉这个愚蠢的问题。这不是一个愚蠢的问题。这是大多数开发人员在其职业生涯中遇到的一个常见问题。我是如何在-2、-3或更多个月前使用相同的代码获取的?
P1M
是“period 1 month”的缩写。因此,要追溯到两个月前,请使用
P2M
。三个月将是P3M等,所以我只需要更换P1M?