The date Function
The date
function outputs the date in a specified
format. The first parameter of the function is the
format, and the second optional parameter
is a point in time in timestamp format. If
the second parameter is not specified, the current
time is taken; if specified, the given time is used.
The format is specified using control commands (English letters), and any separators can be inserted between them (hyphens, colons, and so on).
The function accepts the following commands (uppercase letters differ from lowercase ones, pay attention):
U
– the number of seconds elapsed since1
January1970
(i.e., timestamp).z
– the day number from the start of the year.Y
– year,4
digits.y
- year, two digits.m
– month number (with leading zero).n
– month number without a leading zero.d
– day of the month, always two digits (the first can be zero).j
– day of the month without a leading zero.w
– day of the week (0 - Sunday, 1 - Monday, etc.).h
– hours in12
- hour format.H
– hours in24
- hour format.i
– minutes.s
– seconds.L
–1
if it's a leap year,0
if not.W
– the sequential number of the week of the year.t
– the number of days in the specified month.
Syntax
date(string $format, ?int $timestamp = null): string
Examples of Using date
<?php
// All examples are shown for the date 01.06.2013 at 12.23.59, Monday
echo date('Y'); // outputs '2013'
echo date('y'); // outputs '13'
echo date('m'); // outputs '06' - month number
echo date('d'); // outputs '01' - day of the month
echo date('j'); // outputs '1' - day of the month (without leading zero)
echo date('w'); // outputs '1' - Monday
echo date('H'); // outputs '12' - hours
echo date('i'); // outputs '23' - minutes
echo date('s'); // outputs '59' - seconds
echo date('d-m-Y'); // outputs '01-06-2013'
echo date('d.m.Y'); // outputs '01.06.2013'
echo date('H:i:s d.m.Y'); // outputs '12:23:59 01.06.2013'
?>
The Second Parameter of the date Function
The date
function has a second optional
parameter, which accepts a point in time
in timestamp format. If you pass this parameter,
the date function will format not the current
time, but the one passed as the second
parameter. This timestamp
can be obtained,
for example, via mktime
(but not necessarily):
<?php
echo date('d-m-Y', mktime(0, 0, 0, 12, 29, 13)); // outputs '29-12-2013'
?>
This can be used to find out
the day of the week for a specific date - simply
pass it as the second parameter using
the mktime
function, and use the control character
'w'
as the first parameter:
<?php
// Let's find out what day of the week was 29-12-2013:
echo date('w', mktime(0, 0, 0, 12, 29, 13)); // outputs '0' - Sunday
?>
See Also
-
the
mktime
function,
which returns a point in time in timestamp format