2009-08-28 12 views
4

が主な問題は、自分のサイト上にあるタイムスタンプを取るし、あなたに23日3時間4分6秒PHPの時差機能を改善できますか?以下

の形式で、今から経過した時間を教えてくれる私の関数である私は、MySQLのDATETIMEを使用しますTIMESTAMPの代わりにこの関数を使用するには、私のdatetimeをmysqlからタイムスタンプに変換してから、それを私の関数を通して実行する必要があります。

私は好奇心が強いです、私は100のmysqlの結果があるいくつかのページで、これを行うより良い方法があります、PHPは100の日付をタイムスタンプに変換し、100で実行する必要があります。そこに、より良い性能の方法で、かつ/任意のヒントに感謝、すべてのPHPフレームワーク(Zendの、など)

をお勧めします

function duration($timestamp) { 
    $years = floor($timestamp/(60 * 60 * 24 * 365)); 
    $timestamp %= 60 * 60 * 24 * 365; 
    $weeks = floor($timestamp/(60 * 60 * 24 * 7)); 
    $timestamp %= 60 * 60 * 24 * 7; 
    $days = floor($timestamp/(60 * 60 * 24)); 
    $timestamp %= 60 * 60 * 24; 
    $hrs = floor($timestamp/(60 * 60)); 
    $timestamp %= 60 * 60; 
    $mins = floor($timestamp/60); 
    $secs = $timestamp % 60; 
    $str = ""; 
    if ($years == 1) { 
     $str .= "{$years} year "; 
    }elseif ($years > 1) { 
     $str .= "{$years} yearss "; 
    } 
    if ($weeks == 1) { 
     $str .= "{$weeks} week "; 
    }elseif ($weeks > 1) { 
     $str .= "{$weeks} weeks "; 
    } 
    if ($days == 1) { 
     $str .= "{$days} day "; 
    }elseif ($days > 1) { 
     $str .= "{$days} days "; 
    } 
    if ($hrs == 1) { 
     $str .= "{$hrs} hour "; 
    }elseif ($hrs > 1) { 
     $str .= "{$hrs} hours "; 
    } 
    if ($mins == 1) { 
     $str .= "{$mins} minute "; 
    }elseif ($mins > 1) { 
     $str .= "{$mins} minutes "; 
    } 
    if ($mins < 1 && $secs >= 1) { 
     $str .= "{$secs} seconds "; 
    } 
    return $str; 
} 

答えて

6

を取るか助けないでください場合、私はちょうど疑問に思って

timeのドキュメントをthe PHP siteに見てください。特にthisおよびthis。ここで

は似ているスニペットby Aidan Listerです:

/** 
* A function for making time periods readable 
* 
* @author  Aidan Lister <[email protected]> 
* @version  2.0.0 
* @link  http://aidanlister.com/2004/04/making-time-periods-readable/ 
* @param  int  number of seconds elapsed 
* @param  string which time periods to display 
* @param  bool whether to show zero time periods 
*/ 
function time_duration($seconds, $use = null, $zeros = false) 
{ 
    // Define time periods 
    $periods = array (
     'years'  => 31556926, 
     'Months' => 2629743, 
     'weeks'  => 604800, 
     'days'  => 86400, 
     'hours'  => 3600, 
     'minutes' => 60, 
     'seconds' => 1 
     ); 

    // Break into periods 
    $seconds = (float) $seconds; 
    foreach ($periods as $period => $value) { 
     if ($use && strpos($use, $period[0]) === false) { 
      continue; 
     } 
     $count = floor($seconds/$value); 
     if ($count == 0 && !$zeros) { 
      continue; 
     } 
     $segments[strtolower($period)] = $count; 
     $seconds = $seconds % $value; 
    } 

    // Build the string 
    foreach ($segments as $key => $value) { 
     $segment_name = substr($key, 0, -1); 
     $segment = $value . ' ' . $segment_name; 
     if ($value != 1) { 
      $segment .= 's'; 
     } 
     $array[] = $segment; 
    } 

    $str = implode(', ', $array); 
    return $str; 
} 
関連する問題