Snippets

Bharath Lohray An implementation of ago() in PHP

Created by Bharath Lohray
<?php
/*
    Bharath's implementation of ago() function.
    June 1st 2015.
*/
function ago($time){
    $currentTS=time();
    $diffSec=$currentTS-$time;
    
    $days=intval($diffSec/86400);
    $resH=$diffSec%86400;
    $hours=intval($resH/3600);
    $resM=$resH%3600;
    $minutes=intval($resM/60);
    $seconds=$resM%60;
    
    $agoStr="";
    $dayStr=" day".(($days>1)?"s ":" ");
    $hourStr=" hour".(($hours>1)?"s ":" ");
    $minStr=" minute".(($minutes>1)?"s ":" ");
    $secStr=" seconds ";
    
    $largerMeasure=false;
    if ($days!=0){
        $agoStr.=$days." ".$dayStr;
        $largerMeasure=true;
    }
    if (!($largerMeasure==false && $hours==0)){
        $agoStr.=$hours.$hourStr;
        $largerMeasure=true;
    }
    if (!($largerMeasure==false && $minutes==0)){
        $agoStr.=$minutes.$minStr;
        $largerMeasure=true;
    }
    if (!($largerMeasure==false && $seconds==0)){
        $agoStr.=$seconds.$secStr." ago";
        $largerMeasure=true;
    }
    if ($largerMeasure==false){
        $agoStr="now";
    }
    return $agoStr;
}
$ct=time();
echo "The time now is ".$ct."<br/>";
echo ($ct)." was ".ago($ct)."<br/>";
echo ($ct-1)." was ".ago($ct-1)."<br/>";
echo ($ct-2)." was ".ago($ct-2)."<br/>";
echo ($ct-59)." was ".ago($ct-59)."<br/>";
echo ($ct-60)." was ".ago($ct-60)."<br/>";
echo ($ct-61)." was ".ago($ct-61)."<br/>";
echo ($ct-120)." was ".ago($ct-120)."<br/>";
echo ($ct-3599)." was ".ago($ct-3599)."<br/>";
echo ($ct-3600)." was ".ago($ct-3600)."<br/>";
echo ($ct-3601)." was ".ago($ct-3601)."<br/>";
echo ($ct-3661)." was ".ago($ct-3661)."<br/>";
echo ($ct-3761)." was ".ago($ct-3761)."<br/>";
echo ($ct-86400)." was ".ago($ct-86400)."<br/>";
echo ($ct-90060)." was ".ago($ct-90060)."<br/>";
?>

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.