PHP Date and Time Functions
The date Function
The date function outputs the current date
and time in a specified format. The format is defined
by control commands (English letters),
and any separators can be inserted
between them (hyphens, colons, etc.).
Here are these commands:
U– number of seconds since1January1970(i.e.,timestamp).z– day of the year.Y– year,4digits.y- year, two digits.m– month number (with leading zero).n– month number without leading zero.d– day of the month, always two digits (the first can be zero).j– day of the month without 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–1if leap year,0if not leap year.W– week number of the year.t– number of days in the specified month.
Examples of Using date
<?php
// All examples are shown for the date 01.06.2013 at 12.23.59, Monday
echo date('Y'); // returns '2013'
echo date('y'); // returns '13'
echo date('m'); // returns '06' - month number
echo date('d'); // returns '01' - day of the month
echo date('j'); // returns '1' - day of the month (without leading zero)
echo date('w'); // returns '1' - Monday
echo date('H'); // returns '12' - hours
echo date('i'); // returns '23' - minutes
echo date('s'); // returns '59' - seconds
echo date('d-m-Y'); // returns '01-06-2013'
echo date('d.m.Y'); // returns '01.06.2013'
echo date('H:i:s d.m.Y'); // returns '12:23:59 01.06.2013'
?>
The time Function
The time function returns the difference in
seconds between 1 January 1970
and the current moment in time. This representation
of a date is called the timestamp format. Using
the time function we can only get the current
moment in time. To get a timestamp
for any date, use the
mktime function. See the example:
<?php
echo mktime(12, 43, 59, 1, 31, 2017);
?>
The mktime Function
The mktime function returns a timestamp
for a specified moment in time. The syntax is:
hours, minutes, seconds, day, month, year.
Let's get the timestamp for 31.01.2017
12:43:59:
<?php
echo mktime(12, 43, 59, 1, 31, 2017);
?>
The strtotime Function
The strtotime function is an analogue of the mktime function
(it also returns a timestamp), but unlike
it, accepts a date in a more flexible format.
What else you can do: you can write like this
- strtotime('now') - and we will get
the current moment in time, or like this - strtotime('next
Monday') - and we will get the next Monday
(Monday in English 'понедельник').
See the example:
<?php
echo strtotime('now');
echo strtotime('10 September 2000');
echo strtotime('+1 day');
echo strtotime('+1 week');
echo strtotime('+1 week 2 days 4 hours 2 seconds');
echo strtotime('next Thursday');
echo strtotime('last Monday');
?>