note 50941 added to function.mktime

From: Date: Mon, 14 Mar 2005 16:12:25 +0000
Subject: note 50941 added to function.mktime
Groups: php.notes 
Request: Send a blank email to php-notes+get-86419@lists.php.net to get a copy of this message
For a project I need to use "generic times" - just hours, minutes and seconds that don't represent any particular date. I needed to convert human-readable H:M:S values to timestamp-like integers representing seconds (Example: 00:30:00 becomes 1800). The resulting values are very small; as a result, functions like mktime(), date() & friends think they're dealing with timestamps right around the Unix Epoch. The problem is the Windows / GMT factor. For some values I got warnings about dates before January 1, 1970 not being accepted by Windows. Then other times I would get unexpected values because of my GMT offset (it happens in the best of families). Here's 2 functions that should let you convert back and forth between human-readable H:M:S format and non-negative, GMT-agnostic timestamps for when you are working only with hours, minutes, and seconds. <?php function hms_2_ts($hms) //expects 24 hour time expressed like //00:00:01 for "one second after midnight" { $offset = date(Z); //your local offset in seconds from GMT $hms_arr = explode(":", $hms); $h = $hms_arr[0]; $m = $hms_arr[1]; $s = $hms_arr[2] + $offset; //Compensate for GMT offset $ts = mktime($h, $m, $s, 1, 1, 1970, 0); return $ts; } function ts_2_hms($ts) { $offset = date(Z); $ts += 86400; //no "before 1970" errors on Windows this way. //This will make the date wrong, but we're only //dealing with H:M:S so it shouldn't matter $ts -= $offset; //Compensate for GMT offset return date("H:i:s", $ts); } //Check it out: echo "offset = " . date(Z) . "<br>"; $hms = "00:00:01"; echo "hms = $hms<br>"; $ts = hms_2_ts($hms); echo "ts = $ts<br>"; $hms_again = ts_2_hms($ts); echo "hms again = $hms_again"; ?> ---- Manual Page -- http://www.php.net/manual/en/function.mktime.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+50941 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+50941&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+50941&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+50941&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+50941&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+50941&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+50941&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#86419) next »