Date and time in PHP

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
j Day of the month - (1 - 31) - no leading zeros
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 the current date in the format: 1st Jan 2010
date('J MS Y', mktime(0, 0, 0, 1, 1, 2000));
//outputs 1st Jan 2000

PHP 5 DateTime object

As of PHP 5.2 you can create an object that represents the date and time.

$date = new DateTime('2011-01-31');
$datetime = new DateTime('2011-01-31 12:01:01');

Formatting the date

To format the date you use the same constants as before, but call the format method of the DateTime object.

$date = new DateTime('2011-01-31');
echo $date->format('j/n/Y');
//Outputs 31/1/2011

Related tutorials