Specifications
Validating Dates
You can use the checkdate() function to check whether a date is valid. This is especially use-
ful for checking user input dates. The checkdate() function has the following prototype:
int checkdate (int month, int day, int year)
It will check whether the year is a valid integer between 0 and 32767, whether the month is an
integer between 1 and 12, and whether the day given exists in that particular month. The func-
tion takes leap years into consideration.
For example,
checkdate(9, 18, 1972);
will return true while
checkdate(9, 31, 2000)
will not.
Converting Between PHP and MySQL Date
Formats
Dates and times in MySQL are retrieved in a slightly different way than you might expect.
Times work relatively normally, but MySQL expects dates to be entered year first. For exam-
ple, the 29
th
of August 2000 could be entered as either 2000-08-29 or as 00-08-29. Dates
retrieved from MySQL will also be in this order by default.
To communicate between PHP and MySQL then, we usually need to perform some date con-
version. This can be done at either end.
When putting dates into MySQL from PHP, you can easily put them into the correct format
using the date() function as shown previously. One minor caution is that you should use the
versions of the day and month with leading zeroes to avoid confusing MySQL.
If you choose to do the conversion in MySQL, two useful functions are DATE_FORMAT() and
UNIX_TIMESTAMP().
The DATE_FORMAT() function works similarly to the PHP one but uses different format codes.
The most common thing we want to do is format a date in MM-DD-YYYY format rather than
in the YYYY-MM-DD format native to MySQL. You can do this by writing your query as fol-
lows:
SELECT DATE_FORMAT(date_column, ‘%m %d %Y’)
FROM tablename;
Part Title
P
ART IV
396
23 7842 CH18 3/6/01 3:43 PM Page 396










