有時候外部傳來的時間格式只有秒,如8590秒,
或如time()回傳的時間戳,
為方便進一步使用時間變項或顯示給user,因此常需要做時間的轉換,
其實PHP提供有date(),gmstrftime()等時間處理函數,
這邊隨手記錄下,實作此類function的筆記!
<?php //將秒數自動轉換成小時分鐘秒 //Convert secs to string of day hours and mins function convertSecToStr($secs) { if($secs >= 86400) { $days = floor($secs / 86400); $secs = $secs%86400; $r .= $days.' day'; if($days <> 1) { $r .= 's'; } if($secs > 0) { $r .= ', '; } } if($secs >= 3600) { $hours = floor($secs / 3600); $secs = $secs%3600; $r .= $hours.' hour'; if($hours <> 1) { $r .= 's'; } if($secs > 0) { $r .= ', '; } } if($secs >= 60) { $minutes = floor($secs / 60); $secs = $secs%60; $r .= $minutes.' minute'; if($minutes <> 1) { $r .= 's'; } if($secs > 0) { $r .= ', '; } } $r .= $secs.' second'; if($secs <> 1) { $r .= 's'; } return $r; } $a = '979346'; $string = convertSecToStr($a); echo "{$a} is equal to {$string}"; ?>