Page 131 - Open Soource Technologies 304.indd
P. 131
Open Source Technologies
Notes and most operating systems don’t support negative timestamps, the range in which most of
the PHP date functions operate is January 1, 1970 to January 19, 2038. The PEAR::Date package
handles dates outside this range and also in a platform-independent way.
8.2 Retrieving Date and Time Information
The easiest way of obtaining the current time is with the time( ) function. It accepts no parameters
and simply returns the current timestamp:
<?php
echo time( ); // Outputs something similar to “1077913162”
?>
The resolution is 1 second. If you want some more accuracy, you have two options: microtime()
and gettimeofday(). The microtime() function has one annoying peculiarity: The return value
is a floating-point number containing the decimal part of the timestamp and the number of
seconds since the epoch, concatenated with a space. This makes it, of course, a bit hard to use
for a timestamp with sub-second resolution:
<?php
// Outputs something similar to “0.87395100 1078006447”
echo microtime();
$time = preg_replace(‘@^(.*)\s+(.*)$@e’, ‘\\2 + \\1’,
‘microtime());
echo $time; // Outputs 1078006447.8741
?>
In putting the two parts back together, you lose some of the precision. The gettimeofday() function
has a nicer interface. It returns an array with elements representing the timestamp and additional
microseconds. Two more elements are included in this array, but you cannot really rely on
them because the underlying system functionality—at least in Linux—is not working correctly:
<?php
print_r(gettimeofday());
?>
returns
Array
(
[sec] => 1078006910
[usec] => 339699
[minuteswest] => -60
126 LOVELY PROFESSIONAL UNIVERSITY