差异日期计算

时间:2017-09-12 06:58:43

标签: php laravel date date-arithmetic php-carbon

我使用Carbon计算两个日期之间的差异(包括结束日期)时出现问题。这是问题所在:

我正在使用此代码(来源:danharper在https://laracasts.com/discuss/channels/general-discussion/carbon-display-age-in-years-months-day?page=1中的答案):

$dateFrom = new Carbon("2017-01-01");
$dateTo   = new Carbon("2017-12-31");
$dateTo   = $dateTo->addDay();  //including End Date

echo $dateFrom->diff($dateTo)->format('%y') . " year, <br>";
echo $dateFrom->diff($dateTo)->format('%m') . " month, <br>";
echo $dateFrom->diff($dateTo)->format('%d') . " day <br>";
echo "difference " . $dateFrom->diffInDays($dateTo) . " days <br>";

情景1:

让我们说$date1 = 2017-01-01$date2 = 2017-12-31,然后就会产生结果:

1 year, 0 month, 0 day
difference 365 days

当我在https://www.timeanddate.com/date/durationresult.html?d1=1&m1=1&y1=2017&d2=31&m2=12&y2=2017&ti=on中使用日期计算器时,结果是:

It is 365 days from the start date to the end date, end date included
Or 1 year including the end date

他们得到了同样的答案。的 BUT

情景2:

$date1 = 2017-10-01$date2 = 2017-12-31,然后就会产生结果:

0 year, 3 month, 1 day
difference 92 days

https://www.timeanddate.com/date/durationresult.html?d1=1&m1=10&y1=2017&d2=31&m2=12&y2=2017&ti=on中使用日期计算器,结果如下:

It is 92 days from the start date to the end date, end date included
Or 3 months including the end date

timeanddate.com的结果恰好是3个月。不是 1天

我希望结果 3个月(timeanddate.com的答案)。

我如何实现这个答案?

或者,如果无法实现,是否还有其他技术可以实现: x months y days
(例如:1 jan 20175 feb 2019 = 25 months, 5 days

请帮帮我。

2 个答案:

答案 0 :(得分:0)

您可以更改以下代码,

$dateFrom = new Carbon("2017-01-01");
$dateTo = new Carbon("2017-12-31");
$dateTo   = $dateTo->addDay();  //including End Date

$days = $dateFrom->diffInDays($dateTo);
$months = $dateFrom->diffInMonths($dateTo);
$years = $dateFrom->diffInYears($dateto);

在您的代码中,您已经多次测量差异而不是一次。使用diffInDays()diffInMonths()diffInYears()函数获取两个日期之间的天,月和年的值。

希望你明白。

答案 1 :(得分:0)

情景1

$start_date = new DateTime('1 Jan 2017');
$end_date   = new DateTime('5 Feb 2019 +1 day');

$difference = $start_date->diff($end_date);

$year_diff = $difference->format('%y');
$months_diff = $difference->format('%m');

$total_months = $months_diff + ($year_diff * 12);

$output = $total_months . ' months ' . $difference->format('%d') . ' days';

// would output 25 months 5 days

场景2

$start_date = new DateTime('2017-10-01');
$end_date   = new DateTime('2017-12-31 +1 day');

$difference = $start_date->diff($end_date);

$year_diff = $difference->format('%y');
$months_diff = $difference->format('%m');

$total_months = $months_diff + ($year_diff * 12);

$output = $total_months . ' months ' . $difference->format('%d') . ' days';

// would output 3 months 1 days