geeky · php code

time left php function

just a simple function that returns how many days, hours, minutes and seconds are left given a timestamp i put together. kinda bored so sharing some code XP

give either $time_left (time left in timestamp) or $endtime (an ending timestamp)

/* returns an array of [days],[hours],[minutes],[seconds] time left from now to timestamp given */ 
function timeleft($time_left=0, $endtime=null) { 
	if($endtime != null) 
		$time_left = $endtime - time(); 
	if($time_left > 0) { 
		$days = floor($time_left / 86400); 
		$time_left = $time_left - $days * 86400; 
		$hours = floor($time_left / 3600); 
		$time_left = $time_left - $hours * 3600; 
		$minutes = floor($time_left / 60); 
		$seconds = $time_left - $minutes * 60; 
	} else { 
		return array(0, 0, 0, 0); 
	} 
	return array($days, $hours, $minutes, $seconds); 
}

2 thoughts on “time left php function

  1. i can’t wait to see the new dmb fully-functional and open to the public! you’ve put so much time and coding into it… it’s going to be awesome šŸ˜‰

  2. Thanks for sharing. Here’s the modified functions as formatted string with leading zeros.

    function formatTimeLeft($time_left = 0, $sep = ‘:’) {
    $hours = $minutes = $seconds = 0;
    if($time_left > 0) {
    $hours = floor($time_left / 3600);
    $time_left = $time_left – $hours * 3600;
    $minutes = floor($time_left / 60);
    $seconds = $time_left – $minutes * 60;
    }

    // add leading zeros
    $hours = str_pad($hours, 2, “0”, STR_PAD_LEFT);
    $minutes = str_pad($minutes, 2, “0”, STR_PAD_LEFT);
    $seconds = str_pad($seconds, 2, “0”, STR_PAD_LEFT);

    // format
    $arr = array($hours, $minutes, $seconds);
    return implode($sep, $arr);
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s