In the PHP program, a lot of times will encounter the problem of processing time, such as: Determine how long the user online, a total number of days of login, two posts published the difference between the different operations of the log and so on. In this article, we give an example of how PHP calculates the two-day difference between a year, a month, and a day.
Method One:
/** +----------------------------------------------------------* Function: Calculates two date differences Month Date +----------------------------------------------------------* @param date $date 1 start date * @param date $date 2 deadline Date Date +----------------------------------------------------------* @return Array +------------------------------- ---------------------------*/function diffdate ($date 1, $date 2) {if (Strtotime ($date 1) > Strtotime ($date 2)) {$ YMD = $date 2; $date 2 = $date 1; $date 1 = $ymd; } list ($y 1, $m 1, $d 1) = Explode ('-', $date 1); List ($y 2, $m 2, $d 2) = Explode ('-', $date 2); $y = $m = $d = $_m = 0; $math = ($y 2-$y 1) * + $m 2-$m 1; $y = Round ($math/12); $m = intval ($math% 12); $d = (mktime (0, 0, 0, $m 2, $d 2, $y 2)-mktime (0, 0, 0, $m 2, $d 1, $y 2)/86400; if ($d < 0) {$m-= 1; $d + = date (' J ', Mktime (0, 0, 0, $m 2, 0, $y 2)); } $m < 0 && $y-= 1; Return Array ($y, $m, $d); };
Method Two:
Using the Diff method under datetime
Method Three:
functionDiffdate ($date 1,$date 2){ $datestart=Date(' y-m-d ',Strtotime($date 1)); if(Strtotime($datestart) >Strtotime($date 2)){ $tmp=$date 2; $date 2=$datestart; $datestart=$tmp; } List($Y 1,$m 1,$d 1)=Explode(‘-‘,$datestart); List($Y 2,$m 2,$d 2)=Explode(‘-‘,$date 2); $Y=$Y 2-$Y 1; $m=$m 2-$m 1; $d=$d 2-$d 1; if($d<0){ $d+ = (int)Date(' t ',Strtotime("-1 month$date 2")); $m--; } if($m<0){ $m+=12; $y--; } if($Y= = 0){ return $m.‘ Months '.$d.‘ Days; }ElseIf($Y= = 0 &&$m= = 0){ return $d.‘ Days; }Else{ return $Y.‘ Years '.$m.‘ Months '.$d.‘ Days; }}
PHP calculates two date time difference (returns year, month, day)