note 52558 added to function.mktime

From: Date: Thu, 05 May 2005 16:42:44 +0000
Subject: note 52558 added to function.mktime
Groups: php.notes 
Request: Send a blank email to php-notes+get-88970@lists.php.net to get a copy of this message
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" :) ---- Manual Page -- http://www.php.net/manual/en/function.mktime.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+52558 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+52558&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+52558&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+52558&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+52558&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+52558&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+52558&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#88970) next »