PHP

PHP Convert Duration Time Stamp to date() Syntax

I fond out while using:

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

To display time durations 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:

function getTimeString()
{
    $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 without fear of DST or other time factors intervening.

Note: This function is without optimisations

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