仅在 PHP 中获取两个日期之间的时间(以月为单位)?

Get time between two dates in months only in PHP?

我写这个脚本是为了告诉两个日期之间的时间

$term_start   = date_create("2018-01-01");
$now          = date_create(date("2019-02-01"));
$diff         = date_diff($term_start,$now);
$amount_spent = $diff->format("%y %m");
echo $amount_spent;

但我只想要它几个月后如何强制它输出 25 而不是 1 1?

如果目的是获取两个日期之间的月份差异,那么您可以尝试以下操作:

<?php
$term_start   = date_create("2017-01-01");
$now          = date_create(date("2019-02-01"));
$diff         = date_diff($term_start,$now);
$amount_spent = $diff->format("%y")*12 + $diff->format("%m");
echo $amount_spent;
?>

输出:

25

试试这个代码:

$term_start = "2017-01-01";
$now        = "2019-02-01";
$ts1        = strtotime($term_start);
$ts2        = strtotime($now);
$year1      = date('Y', $ts1);
$year2      = date('Y', $ts2);
$month1     = date('m', $ts1);
$month2     = date('m', $ts2);
$diff       = (($year2 - $year1) * 12) + ($month2 - $month1);
echo $diff;

Output: 25

一个简单的解决方案是计算差值的秒数,然后除以一个月(平均 30 天)的秒数。

$term_start   = "2017-01-01";
$now          = "2019-02-01";
echo floor((strtotime($now) - strtotime($term_start))/2592000);
// 25

这意味着您不需要使用非常繁重的 DateTime。