PHP

PHP convert duration timestamp to date() syntax

I fond out while using:

date('H:i:s', $time);

That it actually returns incorrectly. It would keep returning an extra hour. I found this was due to DST. So I quickly put my thinking cap on and botched together this:

<?php
    function get_time_string(){
        $time = 3600+(60*32)+(50); // 01:32:50
        $time_string = '';

	$hours = (int)($time/(60*60));
	if(strlen($hours) > 1){
		$time_string = $hours.':';
	}else{
		$time_string = '0'.$hours.':';
	}

	$minutes = (int)(($time%(60*60))/(60));
	if($minutes >= 1){
		if(strlen($minutes) > 1){
			$time_string .= $minutes.':';
		}else{
			$time_string .= '0'.$minutes.':';
		}

		$seconds = (int)(($time%(60*60))%(60));
		if(strlen($seconds) > 1){
			$time_string .= $seconds;
		}else{
			$time_string .= '0'.$seconds;
		}
	}else{
		$time = (int)$time;
		if(strlen($time) > 1){
			$time_string .= '00:'.$time;
		}else{
			$time_string .= '00:0'.$time;
		}
	}
	return $time_string;
    }
?>

This function will now correctly convert any timestamp into the needed date notation with fear of DST or other time factors intervening.

This function is without optimisations however if you feel bold and have made the changes needed to make this function faster feel free to post it and I’ll update my post.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s