Like most programming languages, PHP comes with a fairlyfull-featured API for date and time value manipulation. You've probablyused it in your applications, but never bothered to look too closely atit. Well, here's your chance to rectify that mistake - this articledelves into the date/time API in depth, uncovering some hidden nuggetsand demonstrating how it can be used to simplify date and timeprocessing in your PHP scripts.
If you don't like mktime(), you can also use the time() function, which returns the current timestamp (note that you cannot use this function to generate arbitrary timestamps, as is possible with mktime()).
If you need greater accuracy in your timestamp, take a look at the microtime() function, which returns a timestamp in seconds, together with an additional microsecond component. These two values can be added together to obtain a more precise timestamp value. Like time(), this function too cannot be used with arbitrary dates and times - it only returns a timestamp for the current instant.
The microtime() function is particularly useful when you need to time events accurately, or when you need an arbitrary, unique number to seed PHP's random number generator. Here's an example of the former:
<?
// function to calculate timestamp in microseconds
function tscalc()
{
// split returned timestamp
$arr = explode(" ", microtime());
// add microseconds to seconds
// to generate more precise timestamp
return $arr[0] + $arr[1];
}
// start time
$start = tscalc();
// do something
// over here, run a loop
$count = 0;
$x = 0;
while ($count < 500)
{
$x = $x + $count;
$count++;
}
// end time
$end = tscalc();
echo "Started at $start";
echo "Ended at $end";
echo "Total processing time was " . ($end-$start);
?>
And here's an example of the latter:
<?
// function to calculate timestamp in microseconds
function tscalc()
{
// split returned timestamp
$arr = explode(" ", microtime());
// add microseconds to seconds
// to generate more precise timestamp
return $arr[0] + $arr[1];
}
// seed random number generator
srand(tscalc());
// get a random number
echo rand();
?>