Main Content

Time calculation in PHP

Archive - Originally posted on "The Horse's Mouth" - 2005-07-08 11:25:58 - Graham Ellis

Looking to calculate using time in PHP? Been provided with some timestamps such as
[23/Jun/2005:00:06:54 -0700]? (That example is from an Apache Log file).

Method:
- extract the relevant parts of the date from the string
- convert months to a number
- convert the numbers to seconds from Midnight, 1.1.1970
- you can calculate using the resulting figure!


function getwhen($dateinfo) {
$month = array("Jan" => 1,"Feb" => 2,"Mar" => 3, "Apr" => 4,
"May" => 5, "Jun" => 6, "Jul" => 7, "Aug" => 8,
"Sep" => 9, "Oct" => 10, "Nov" => 11, "Dec" => 12);
# Note - hour, minute, second, month, day, year order!
$ts = mktime($dateinfo[4],$dateinfo[5],$dateinfo[6],
$month[$dateinfo[2]],$dateinfo[1],$dateinfo[3]);
# Time zone correction
$ts -= $dateinfo[7] * 3600;
return $ts;
}

ereg('(..)/(...)/(....):(..):(..):(..) (...)',$first,$startdate);
$timingfrom = getwhen ($startdate);


PHP's date function can be used to convert it the opposite direction - from a value in seconds from 1.1.1970 into a string.