显示两个日期之间的月数

Show number of months between two dates

我想获取两个日期之间的月数,但出现此错误:

DateTime::__construct() expects parameter 1 to be string, object given

这是函数:

function getMonthDiff()
{
    $currentDateTime = new \DateTime;
    $dateTimeInTheFuture = new \DateTime($this->getSalarie()->getDateEmbauche());
    $dateInterval = $dateTimeInTheFuture->diff($currentDateTime);
    $totalMonths = 12 * $dateInterval->y + $dateInterval->m;

    return $totalMonths;

}

这是我在 twig 中的显示方式:

{{ entity.monthDiff }}

这是 getDateEmbauche 函数

public function getDateEmbauche(): ?\DateTimeInterface
{
    return $this->dateEmbauche;
}

如您在 PHP documentation 中所见:

DateTime::__construct Returns new DateTime object

public DateTime::__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

所以 DateTime 需要 String 参数,但你给它一个 DateTime 对象.

改成这样:

function getMonthDiff()
{
    $currentDateTime = new \DateTime;
    $dateTimeInTheFuture = $this->getSalarie()->getDateEmbauche();
    $dateInterval = $dateTimeInTheFuture->diff($currentDateTime);
    $totalMonths = 12 * $dateInterval->y + $dateInterval->m;

    return $totalMonths;

}