Page 519 - Beginning PHP 5.3
P. 519
Chapter 16: PHP and the Outside World
$d = strtotime( “March 28, 2006 9:42am” );
// Displays “March 28, 2006 9:42 AM”
echo date( “F j, Y g:i A”, $d ) . “ < br / > ”;
// Displays “March 28, 2006 2:42 PM”
echo gmdate( “F j, Y g:i A”, $d ) . “ < br / > ”;
Checking Date Values
Often a script needs to work with dates that have been entered by visitors to the site. For example, a Web
form might contain three select menus allowing visitors to enter the month, day, and year of their date
of birth. However, in this scenario there ’ s nothing to stop the visitors entering a date that doesn ’ t exist,
such as February 31, 2009. Obviously it would be a good idea to validate the date fields entered by the
users to make sure they have in fact supplied a legitimate date.
PHP ’ s checkdate() function takes the month number (1 – 12), day number (1 – 31), and year components
of a date, and returns true if the date is valid, or false if it ’ s invalid:
echo checkdate( 2, 31, 2009 ) . “ < br / > ”; // Displays “” (false)
echo checkdate( 2, 28, 2009 ) . “ < br / > ”; // Displays “1” (true)
It ’ s a good idea to call checkdate() on any user - entered date before passing it to, say, mktime() for
conversion to a timestamp.
Working with Microseconds
The date and time functions you ’ ve seen so far in this chapter work with integer timestamps — that is,
timestamps representing whole numbers of seconds. Most of the time this is all you need. If you do need
extra precision, use PHP ’ s microtime() function. As with time() , microtime() returns a timestamp
representing the current time. However, microtime() returns an additional microseconds component,
allowing you to determine the current time more precisely:
// Displays, for example, “0.45968200 1230613358”
echo microtime();
As you can see, microtime() returns a string consisting of two numbers separated by a space. The first
number is the microseconds component, represented as a fraction of a second, and the second number is
the whole number of seconds — that is, the standard integer timestamp. So the example output shown in
the preceding code snippet represents 1,230,613,358.459682 seconds after midnight, Jan 1, 1970 (UTC).
If you prefer, you can get microtime() to return a floating - point number of seconds, rather than a
two - number string, by passing in an argument of true :
// Displays, for example, “1230613358.46”
echo microtime( true );
481
9/21/09 9:15:31 AM
c16.indd 481
c16.indd 481 9/21/09 9:15:31 AM