Você está na página 1de 2

PHP:CalculateRealDifferencesBetweenTwoDatesorTimestamps

byJR|Published:Jan26,2010|Updated:Oct14,2015|217comments

IwasusingsimplefunctiontocalculatedifferencebetweentwodatesandtimestampsuntilInoticed,itsnotworkingcorrectly
inlongintervals.Itsveryeasytocalculatedifferencebetweentwotimestampsinseconds,butitsmuchmorecomplicated
printdifferenceinhumanreadableformat.TheInternetcanbefoundinawiderangeofwaystodothisthing,butasarulethey
useafixedamountofsecondsfortheyearandthemonth.Soifwecalculateyearwithusing365or365.25daysandmonth
using30or31thenthedifferenceisnotaccurate,becauseofleapyears,DST(DaylightSavingTime)andsoon.
Becauseofthisproblem,Idecidedtomakeafunction(atleastintheshorttesting)toreturntherightkindofdifferences
betweentheUNIXtimestampsanddatesinhumanreadableformat.ThisfunctionusesPHPstrtotimefunctiontocalculatereal
differencesandcanhandleleapyearsandDST.ThisfunctioncanalsoreturnTwitterlikeabouttextswithprecisionparameter.

PHPdateDifffunctionforcalculatingrealdifferencesbetweendatesandUNIX
timestamps

<?php

//Settimezone
date_default_timezone_set("UTC");

//TimeformatisUNIXtimestampor
//PHPstrtotimecompatiblestrings
functiondateDiff($time1,$time2,$precision=6){
//Ifnotnumericthenconverttextstounixtimestamps
if(!is_int($time1)){
$time1=strtotime($time1);
}
if(!is_int($time2)){
$time2=strtotime($time2);
}

//Iftime1isbiggerthantime2
//Thenswaptime1andtime2
if($time1>$time2){
$ttime=$time1;
$time1=$time2;
$time2=$ttime;
}

//Setupintervalsanddiffsarrays
$intervals=array('year','month','day','hour','minute','second');
$diffs=array();

//Loopthruallintervals

foreach($intervalsas$interval){
//Createtemptimefromtime1andinterval
$ttime=strtotime('+1'.$interval,$time1);
//Setinitialvalues
$add=1;
$looped=0;
//Loopuntiltemptimeissmallerthantime2
while($time2>=$ttime){
//Createnewtemptimefromtime1andinterval
$add++;
$ttime=strtotime("+".$add."".$interval,$time1);
$looped++;
}

$time1=strtotime("+".$looped."".$interval,$time1);
$diffs[$interval]=$looped;
}

$count=0;
$times=array();
//Loopthrualldiffs
foreach($diffsas$interval=>$value){
//Breakifwehaveneededprecission
if($count>=$precision){
break;
}
//Addvalueandinterval
//ifvalueisbiggerthan0
if($value>0){
//Addsifvalueisnot1
if($value!=1){
$interval.="s";
}
//Addvalueandintervaltotimesarray
$times[]=$value."".$interval;
$count++;
}
}

//Returnstringwithtimes
returnimplode(",",$times);
}

?>

ConvertingtextformatbacktoUNIXtimestampexample:

dateDifffunctionexampleusage

$time1=time();
$time2=$time110000000;
echo$diff=dateDiff($time1,$time2)."\n";
echo$time1."\n";
echostrtotime("+".$diff,$time2)."\n";

strtotimeexamples:

Output:
3months,23days,17hours,46minutes,40seconds
1264514564
1264514564

echodateDiff("20100126","20040126")."\n";
echodateDiff("2006041212:30:00","1987041212:30:01")."\n";
echodateDiff("now","now+2months")."\n";
echodateDiff("now","now6year2months10days")."\n";
echodateDiff("20090126","2004012615:38:11")."\n";

Output:
6years
18years,11months,30days,23hours,59minutes,59seconds
2months
6years,2months,10days
4years,11months,30days,8hours,21minutes,49seconds

UNIXtimestampandprecisionexamples

echodateDiff(time(),time()1000000,1)."\n";
echodateDiff(time(),time()1000000,3)."\n";
echodateDiff(time(),time()1000000,6)."\n";

Output:

11days
11days,13hours,46minutes
11days,13hours,46minutes,40seconds

Você também pode gostar