| | |||||||
| |||||||
| |||||||
|
|
|
|
|
|
|
sec_to_time(), sec_to_string(), string_to_sec(), time_diff() By : voldomazta <? /** * Time Functions * by: Ramon Alivio Jr. * on: 2005-06-17 **/ class Time { /** * Returns the time of the day using an integer argument which means the number of seconds from 12:00:00AM * Examples : 32563 (09:02 AM), 53447 (2:50 PM) **/ function sec_to_string($s,$f = '') { $h = floor($s/3600); $m = floor($s/60) - ($h * 60); $ts = $s - ($h * 3600) - ($m * 60); $hours = (strlen($h) == 1 ? '0'.$h : $h); $minutes = (strlen($m) == 1 ? '0'.$m : $m); $seconds = (strlen($ts) == 1 ? '0'.$ts : $ts); $meridian = ' '.($h == 12 ? 'NN' : ($h > 12 ? 'PM' : 'AM')); if($h > 24) return 'Invalid Time'; switch($f) { case 12: return ($hours > 12 ? $hours-12 : $hours).':'.$minutes.$meridian; case 24: return $hours.':'.$minutes; break; default: return $hours.':'.$minutes.':'.$seconds; break; } } /** * A reverse of sec_to_string() * Returns the number of seconds from 12:00:00AM using a string argument of the current time of the day. * Example Arguments : 6:02:54PM (64974), 11:05AM (39900) **/ function string_to_sec($time) { preg_match("/([0-9]{0,2})\:([0-9]{0,2})\:?([0-9]{0,2})?\s?([a|A|p|P|n|N])([m|M|n|N])/",$time,$matches); $hours = $matches[1]; $minutes = $matches[2]; $seconds = (empty($matches[3]) ? '00' : $matches[3]); $meridian = strtoupper($matches[4].$matches[5]); if($hours > 12 || $hours < 0) return false; switch($meridian) { case 'AM': if($hours == 12) $hours = 0; break; case 'NN': if($hours > 12 || $hours < 12) return false; $add = 0; break; case 'PM': if($hours == 12) return false; $add = 43200; break; default: $add = 0; break; } return (int)(($hours * 3600) + ($minutes * 60) + $seconds + $add); } /** * Returns the HH:mm:ss format of an integer. 1 being 00:00:01 * Examples: 5321 (01:28:41); **/ function sec_to_time($sec) { $diff = ($sec < 0 ? ($sec * -1) : $sec); $h = floor($diff/3600); $m = floor($diff/60) - ($h * 60); $ts = $diff - ($h * 3600) - ($m * 60); $hours = (strlen($h) == 1 ? '0'.$h : $h); $minutes = (strlen($m) == 1 ? '0'.$m : $m); $seconds = (strlen($ts) == 1 ? '0'.$ts : $ts); return $hours.':'.$minutes.':'.$seconds; } /** * Returns the number of hours, minutes and seconds between two times in a single day * Examples: 12:00:00AM or 12:00AM * Arguments are interchangeable **/ function time_diff($time1,$time2) { $newtime1 = $this->string_to_sec($time1); $newtime2 = $this->string_to_sec($time2); if(!$newtime1 || !$newtime2) return false; return $this->sec_to_time($newtime1 - $newtime2); } } ?>
More Date Time Code Articles |
| |
| |