PHP将日期间隔diff转换为十进制 [英] PHP convert date interval diff to decimal
问题描述
我正在尝试将两个日期之间的差异转换为总计数,现在我使用这个:
I'm trying to convert the difference between two dates into a total year count, right now I'm using this:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2010-10-10');
$interval = $datetime1->diff($datetime2);
return $interval->format('%y');
这将返回一个int(对于<一年,0年,两年两年等) 。)
This returns me an int (Like 0 for < than a year, 2 for two years, etc.)
我需要结果为十进制如下:
I need the result to be decimal as following:
0.9 - 9个月
0.9 - 9 months
1.2 - 1年零2个月
1.2 - 1 year and two months
3.5 - 3年零5个月
3.5 - 3 years and five months
等等。
谢谢!
推荐答案
p>如果您不在乎完美的准确性:
If you don't care about perfect accuracy:
return $interval->days / 365;
您还可以执行类似 return $ interval-> y + $间隔 - > m / 12 + $ interval-> d / 365
。
甚至没有注意到你的奇怪的十进制约定,直到我看到@ 2unco的评论。这将是: return $ interval-> y。 '''。 $ interval-> m
。
Didn't even notice your weird decimal convention until I saw @2unco's comment. That would look like: return $interval->y . '.' . $interval->m
.
这篇关于PHP将日期间隔diff转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!