note 50941 deleted from function.mktime by derick
| From: | derick@php.net | Date: | Sun, 24 Sep 2006 12:01:32 +0000 |
| Subject: | note 50941 deleted from function.mktime by derick | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-117517@lists.php.net to get a copy of this message | ||
Note Submitter: Greg Robbins
----
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";
?>