The date function

PHP has a very useful date function that can read in a Unix timestamp and output the date as a formatted string of your choice.

date(format [, optional Unix timestamp])

The timestamp is optional, if it is left out it will default to the current time.

Unix time stamps

An easy way to create Unix timestamps for use with the date function is to use mktime.

mktime([optional hour, minute, second, month, day, year])

All parameters in mktime are optional (from left to right i.e. if you want to specify a day then you have to specify a month), if they are left out they will default to the current date and time.

Date format string

Below are a list of common strings for the date function.

Format character Description
aam - pm
AAM - PM
dDay of the month - (01 - 31) - leading zeros
DDay of the week - 3 letters e.g. Mon
FMonth of the year - full - e.g. January
g12 hour format - (1 - 12 )
G24 hour format - (0 - 23)
h12 hour format - (01 - 12 ) - leading zeros
H24 hour format - (00 - 23) - leading zeros
iMinutes - (00 - 59) - leading zeros
JDay of the month - (1 - 31)
lDay of the week - Full - e.g. Monday
LLeap year - (1=leap year)
mMonth of the year - numerical - (01 - 12) - leading zeros
MMonth of the year - 3 letters - e.g. Jan
nMonth of the year - numerical - (1 - 12)
ODifference to Greenwich mean time e.g. +0200
sSeconds with leading zeros - (00-59)
SSuffix of day of the month - e.g. st, nd, rd, th
tNumber of days in the month
TTime zone
wNumerical day of the week - (0 = Sunday, 1 = Monday)
WWeek of the year
YYear - full - 2005
yYear - 2 numbers - 05
zDay of year

For the full list see the PHP website.

Examples

Below are a list of example uses of the date function.

date('J MS Y');
//outputs 1st Jan 2010
date('J MS Y', mktime(0, 0, 0, 1, 1, 2000));
//outputs 1st Jan 2000
Adobe Fireworks® Adobe Flash® and Adobe Photoshop® are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries.
MySQL is a registered trademark of MySQL AB in the United States, the European Union and other countries.
Copyright Pixelcode 2005 - 2010