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 usemktime
.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 thedate
function.Format character | Description |
---|---|
a | am – pm |
A | AM – PM |
d | Day of the month – (01 – 31) – leading zeros |
D | Day of the week – 3 letters e.g. Mon |
F | Month of the year – full – e.g. January |
g | 12 hour format – (1 – 12 ) |
G | 24 hour format – (0 – 23) |
h | 12 hour format – (01 – 12 ) – leading zeros |
H | 24 hour format – (00 – 23) – leading zeros |
i | Minutes – (00 – 59) – leading zeros |
j | Day of the month – (1 – 31) – no leading zeros |
l | Day of the week – Full – e.g. Monday |
L | Leap year – (1=leap year) |
m | Month of the year – numerical – (01 – 12) – leading zeros |
M | Month of the year – 3 letters – e.g. Jan |
n | Month of the year – numerical – (1 – 12) |
O | Difference to Greenwich mean time e.g. +0200 |
s | Seconds with leading zeros – (00-59) |
S | Suffix of day of the month – e.g. st, nd, rd, th |
t | Number of days in the month |
T | Time zone |
w | Numerical day of the week – (0 = Sunday, 1 = Monday) |
W | Week of the year |
Y | Year – full – 2005 |
y | Year – 2 numbers – 05 |
z | Day of year |
Examples
Below are a list of example uses of thedate
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 theformat
method of the DateTime
object.$date = new DateTime('2011-01-31');
echo $date->format('j/n/Y');
//Outputs 31/1/2011
0 Comments
Good day precious one, We love you more than anything.