我在用碳计算两个日期(,包括结束日期)之间的差异时遇到了问题。问题是:
我正在使用以下代码(https://laracasts.com/discuss/channels/general-discussion/carbon-display-age-in-years-months-day?page=1中的danharper的答案):
$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他们得到了同样的答案。但
场景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 datetimeanddate.com的结果正好是3个月的仅为。不使用1天。
我想要的结果是3个月(timeanddate.com的答案)。
我怎样才能得到这个答案呢?
或者,如果无法实现,是否还有其他技术可实现:x months y days?
(ex:1 jan 2017 ~ 5 feb 2019 = 25 months, 5 days)
请帮帮我。
发布于 2017-09-12 07:22:57
您可以像下面这样更改代码,
$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()函数获得两个日期之间的天数、月份和年份的值。
希望你能理解。
发布于 2017-09-12 10:49:41
场景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 dayshttps://stackoverflow.com/questions/46169893
复制相似问题