Date and Time Functions

The basic PHP date and time functions let you format timestamps for use in database queries or simply for displaying the date and time in the browser window. PHP includes the following date and time functions:

date(format) - Returns the current server time, formatted according to a given set of parameters.

checkdate(month, day, year) - Validates a given date. Successful validation means that the year is between 0 and 32767, the month is between 1 and 12, and the proper number of days in each month.

time() - Returns the current server time, measured in seconds since the Epoch or January 1, 1970.

The table below contains valid date() formats:

aPrints "am" or "pm"
APrints "AM" or "PM".
hHour in 12-hour format (01 to 12)
HHour in 24-hour format (00 to 23)
gHour in 12-hour format without a leading zero (1 to 12)
GHour in 24-hour format without a leading zero (0 to 23)
iMinutes (00 to 59)
sSeconds (00 to 59)
dDay of the month in two digits (01 to 31)
DDay of the week in text (Mon to Sun)
lDay of the week in long text (Monday to Sunday)
FMonth in long text (January to December)
nMonth in two digits (1 to 12)
YYear in four digits (2005)
yYear in two digits (05)
sEnglish ordinal suffix (th, nd, st)

The following page uses the PHP date function to determine and display the current server time and date:

<?php

echo "<span style='font:10pt arial'>Today is date('lFjY')</span>";

echo "<br/>";

echo "<span style='font:10pt arial'>The current time is: date('g:i:s a')</span>";

?>


The format of the date/time displayed using the date() function depends on the types of format parameters supplied to the function. The date function parameters can be combined, separated by a comma ",", separated by a colon ":", or other punctuation marks depending on the output format desired. All parameters, however, should be enclosed by single quotes. In the example above, the time is displayed using the time format parameters g, i, s, and a. Colons and blank spaces are also inserted to separate the hours, minutes, seconds and am/pm designation.

The checkdate() and time() functions are typically used in decision making processes. For this reason, these functions will be discussed in more detail in a later tutorial.