Countdown between two unix timestamps


Here is a way to display the day/hour/min difference between two unix timestamps, fx

6 days 6 hours 37 minutes

Here is the above example

<?php 
$future_time=1353628800; 
$current_time=time(); 
echo countdown($current_time,$future_time); 
?>

and here is the function where you can translate/change the labels:

<?php 
/**  
* Calculates the number of days, hours and minutes 
* between two Unix timestamps.  
*  
* The Unix timestamp $t2 should be greater than $t1  
*  
* @param integer $t1 Date with Unix timestamp format.  
* @param integer $t2 Date with Unix timestamp format.  
* @return string Formatted string 
* fx: 3 days 5 hours 23 minutes  
*/ 
function countdown($t1,$t2){         
        // t2 > t1

        // setup
        $out ="";
        $days_label=" days ";
        $day_label=" day ";
        $hours_label=" hours ";
        $hour_label=" hour ";
        $mins_label=" minutes ";
        $min_label=" minute "i
        $timeup_label=" ho ho - the time is up";

        // calculate
        $diff=$t2-$t1;
        $d=$diff/86400;
        $days=(int)$d;
        $h=($d-$days)*24;
        $hours=(int)$h;
        $m=($h-$hours)*60;
        $mins=(int)$m;

        // find out the labels (singular/plural)
        $d_label=($days==1)?$day_label:$days_label;
        $h_label=($hours==1)?$hour_label:$hours_label;
        $m_label=($mins==1)?$min_label:$mins_label;

        // output
        if($days>0){
                $out.= $days.$d_label;
        }
        if($hours>0){
                $out.= $hours.$h_label;
        }
        if($mins>0){
                $out.= $mins.$m_label;
        }
        if($days+$hous+$mins <= 0 ){
                $out=$timeup_label;
        }

        return $out;
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*