Home  >  Article  >  Backend Development  >  程序员 - PHP时间问题,2014-1-21 和 2013-5-13 请用最有效率的方法计算出两个时间相差的年份和月份??

程序员 - PHP时间问题,2014-1-21 和 2013-5-13 请用最有效率的方法计算出两个时间相差的年份和月份??

WBOY
WBOYOriginal
2016-06-06 20:46:421092browse

PHP时间问题,2014-1-21 和 2013-5-13 请用最有效率的方法计算出两个时间相差的年份和月份??年份和月份用int类型表示

回复内容:

PHP时间问题,2014-1-21 和 2013-5-13 请用最有效率的方法计算出两个时间相差的年份和月份??年份和月份用int类型表示

https://github.com/briannesbitt/Carbon

<code>$dt1 = Carbon\Carbon::createFromDate(2014, 1, 21);
$dt2 = Carbon\Carbon::createFromDate(2013, 5, 13);

echo $dt1->diffInYears($dt2);    //0
echo $dt1->diffInMonths($dt2);    //8
echo $dt1->diffInDays($dt2);    //253
echo $dt1->diffInHours($dt2);    //6072
echo $dt1->diffInMinutes($dt2);    //364320
echo $dt1->diffInSeconds($dt2);    //21859200
</code>

是截至到2014-1-21的00:00:00还是到23:59:59


1.

<code class="lang-php">echo (new DateTime('2014-3-15'))->diff(new DateTime('2014-5-10'))->format('两个时间相差 %y 年 %m 月 %d 天.');
</code>

2.

<code class="lang-php">$ts1 = strtotime('2014-3-15');
$ts2 = strtotime('2014-5-10');
$ts = $ts1 > $ts2 ? $ts1 - $ts2 : $ts2 - $ts1;
echo (new DateInterval($ts))->format('两个时间相差 %y 年 %m 月 %d 天.');
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn