Date and Time Functions

There are several PHP library functions that work with dates and times. Most either generate a Unix timestamp or format a Unix timestamp in a human-readable form.

Generating a Timestamp

Date and time is generally represented as a Unix timestamp: the number of seconds since 1 January 1970 00:00:00 Greenwich Mean Time. Most systems represent a timestamp using a signed 32-bit integer, allowing a range of dates from December 13, 1901 through January 19, 2038. While timestamps are convenient to work with in scripts, care must be taken when manipulating timestamps to avoid integer overflow errors. A common source of errors is to compare two timestamps in which the date range is greater than the largest positive integer-a range just over 68 years for a signed 32-bit integer.

PHP gives unexpected results when comparing two integers that differ by an amount greater than the largest positive integer, typically 231-1. A safer way to compare large integers is to cast them to floating-point numbers. The following example illustrates this point:

$var1 = -2106036000;  // 16/08/1902
$var2 = 502808400;    // 24/08/1984
// $result is assigned false
$result = $var1 < $var2;
// $result is assigned true as expected
$result = (float) $var1 < (float) $var2;

Even floating-point numbers can overflow. To manipulate numbers of arbitrary precision, the BCMath library should be considered.

Current time

PHP provides several functions that generate a Unix timestamp. The simplest:

integer time(  )

returns the timestamp for the current date and time, as shown in this fragment:

// prints the current timestamp: e.g., 1008553254
echo time(  );