Here's useful function that calculates the difference between two dates. You can get the result in seconds, minutes, hours, days, weeks, and year. :)
dateDiff() function
//function like dateDiff Microsoft
//not error in year Bissesto
function dateDiff($interval,$dateTimeBegin,$dateTimeEnd) {
//Parse about any English textual datetime
//$dateTimeBegin, $dateTimeEnd
$dateTimeBegin=strtotime($dateTimeBegin);
if($dateTimeBegin === -1) {
return("..begin date Invalid");
}
$dateTimeEnd=strtotime($dateTimeEnd);
if($dateTimeEnd === -1) {
return("..end date Invalid");
}
$dif=$dateTimeEnd - $dateTimeBegin;
switch($interval) {
case "s"://seconds
return($dif);
case "n"://minutes
return(floor($dif/60)); //60s=1m
case "h"://hours
return(floor($dif/3600)); //3600s=1h
case "d"://days
return(floor($dif/86400)); //86400s=1d
case "ww"://Week
return(floor($dif/604800)); //604800s=1week=1semana
case "m": //similar result "m" dateDiff Microsoft
$monthBegin=(date("Y",$dateTimeBegin)*12)+
date("n",$dateTimeBegin);
$monthEnd=(date("Y",$dateTimeEnd)*12)+
date("n",$dateTimeEnd);
$monthDiff=$monthEnd-$monthBegin;
return($monthDiff);
case "yyyy": //similar result "yyyy" dateDiff Microsoft
return(date("Y",$dateTimeEnd) - date("Y",$dateTimeBegin));
default:
return(floor($dif/86400)); //86400s=1d
}
}
Usage
// Get DateTime difference in seconds
$seconds = dateDiff('s', $dateTimeBefore, $dateTimeNow);
echo $seconds;
// Get DateTime difference in minutes
$minutes = dateDiff('n', $dateTimeBefore, $dateTimeNow);
echo $minutes;
// Get DateTime difference in hours
$hours = dateDiff('h', $dateTimeBefore, $dateTimeNow);
echo $hours;
// Get DateTime difference in days
$days = dateDiff('d', $dateTimeBefore, $dateTimeNow);
echo $days;
// Get DateTime difference in Week
$Week = dateDiff('ww', $dateTimeBefore, $dateTimeNow);
echo $Week;
// Get DateTime difference in similar result "m" dateDiff Microsoft
$m = dateDiff('m', $dateTimeBefore, $dateTimeNow);
echo $m;
// Get DateTime difference in similar result "yyyy" dateDiff Microsoft
$yyyy = dateDiff('yyyy', $dateTimeBefore, $dateTimeNow);
echo $yyyy;
No comments:
Post a Comment