note 52558 deleted from function.mktime by derick
| From: | derick@php.net | Date: | Sun, 24 Sep 2006 11:59:58 +0000 |
| Subject: | note 52558 deleted from function.mktime by derick | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-117512@lists.php.net to get a copy of this message | ||
Note Submitter: Greg Robbins
----
Here's an update (no pun intended) to my "generic times" function below for
comverting between timestamps and hours, minutes and seconds, but that don't represent any
particular date.
The previous functions return values that are incorrectly offset by 1 hour (3600 seconds) when you
are in daylight savings time.
Here are revised functions that take into account whether or not you are on daylight savings time.
These 2 functions let you convert back and forth between human-readable H:M:S format and
non-negative, GMT-agnostic (and DST-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
$is_dls = date(I) == 1 ? true : false; //date(I) returns 1 if in DST, 0 if not
if($is_dls) $offset -= 3600; //Roll back one hour if you are in DST
$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);
$is_dls = date(I) == 1 ? true : false; //date(I) returns 1 if in DST, 0 if not
if($is_dls) $offset -= 3600; //Roll back one hour if you are in DST
$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";
?>
I suggest that "Daylight Savings Time" could also be called "Programmers'
Wasting Time" :)