Home  >  Article  >  Backend Development  >  php计算两个日期相隔多少年,多少月,多少日的函数

php计算两个日期相隔多少年,多少月,多少日的函数

WBOY
WBOYOriginal
2016-06-20 13:03:591345browse

在做类似OA这种项目的时候,可能会碰到计算一个员工工龄的情况,这个时候仅仅精确到年或者精确到月是不够的,下面分享一个精确到多少天的函数。可以显示为类似相隔1年25天这种形式的。

<p>/*</p>*function:计算两个日期相隔多少年,多少月,多少天<br />*param string $date1[格式如:2011-11-5]<br />*param string $date2[格式如:2012-12-01]<br />*return array array('年','月','日');<br />*/<br />function diffDate($date1,$date2){<br />	if(strtotime($date1)>strtotime($date2)){<br />		$tmp=$date2;<br />		$date2=$date1;<br />		$date1=$tmp;<br />	}<br />	list($Y1,$m1,$d1)=explode('-',$date1);<br />	list($Y2,$m2,$d2)=explode('-',$date2);<br />	$Y=$Y2-$Y1;<br />	$m=$m2-$m1;<br />	$d=$d2-$d1;<br />	if($d<0){<br />		$d+=(int)date('t',strtotime("-1 month $date2"));<br />		$m--;<br />	}<br />	if($m<0){<br />		$m+=12;<br />		$y--;<br />	}<br />	return array('year'=>$Y,'month'=>$m,'day'=>$d);<br /><p>}</p>

该函数使用方法如下:echo '

';print_r(diffDate('2012-12-1','2011-11-5'));//这两个参数无顺序之分<p>打印结果如下:</p><p>Array</p>(<br>    [year] => 1<br>    [month] => 0<br>    [day] => 26<br><p>)</p><p>以上结果的意思即这两日期相隔1年26天。</p><p class="item-note"><br></p>
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