Let's take a look at how to work with dates and times in PHP.
Time inUnix-computers
For Unix computers, the time starts at midnight on January 1, 1970. Any date is calculated as the number of seconds (denoted by timestamp –– timestamp) that have passed since 01.01.1970. These conventions are also used in PHP. For example, we want to go one day ahead. Then you just need to add 60 × 60 × 24 seconds to the current timestamp value.
This time tracking scheme greatly facilitates the operations with dates. For example, if one timestamp value is greater than another, the first value is later than the second.
Time units per second
Getting the current time
In PHP, to get the current timestamp value, call the time () function without parameters, for example:
Many PHP functions for working with date and time take a timestamp value as an argument. For example, the date () function returns a formatted date string, for example:
Creaturetimestamp by date
Functionmktime() will create a timestamp if you specify hour, minute, second, day of month, month and year:
Functionstrtotime()
The function generates a timestamp for a date specified as a phrase in English, for example, April 1 or Friday.
The date value must be specified in the YYYY-MM-DD format. If the strtotime function cannot convert the date, it returns false.
Examples of using the functiondate ()
The built-in function floor () is used to discard the fractional part of the result.
The following text can be skipped on first reading
Date formats in databasesMySQL
The PHP timestamp format is incompatible with the MySQL timestamp format.
MySQL has three types of date and time fields: DATA (date), TIME (time), DATETIME (date and time). There is also a special data type TIMESTAMP, which works like DATETIME, but is automatically updated to reflect the current time each time a table record is inserted or updated.
To convert a timestamp in PHP format to MySQL format, you can use the following code:
Date ("Y-m-d H: i: s", $ timestamp)
For example, we can use “2008-10-01 13:23:40” as the date and time.
To get the PHP timestamp from a SELECT query, use the UNIX_TIMESTAMP () SQL function:
SELECT UNIX_TIMESTAMP (date) FROM table
MySQL has many other useful functions for working with date and time.
string date(string format[, int timestamp])
Returns the time formatted according to the argument format using the timestamp given by the argument timestamp or the current system time if timestamp not set. In other words, timestamp is optional and defaults to the value returned by the function time () .
Comment: For most systems, valid dates are December 13, 1901, 20:45:54 GMT through January 19, 2038, 03:14:07 GMT. (These dates correspond to the minimum and maximum value of a 32-bit signed integer.) For Windows, the valid dates are 01-01-1970 through 01.19-2038.
Comment: To get a timestamp from a string representation of a date, you can use the function strtotime ()... In addition, some databases have their own functions for converting the internal date representation to a timestamp (for example, the MySQL UNIX_TIMESTAMP function).
The following characters are recognized in the format parameter
The character in the format string | Description | Return value example |
---|---|---|
a | Ante meridiem or Post meridiem in lower case | am or pm |
A | Ante meridiem or Post meridiem in uppercase | AM or PM |
B | Swatch Internet time | 000 to 999 |
c | Date in ISO 8601 format (added in PHP 5) | 2004-02-12T15: 19: 21 + 00: 00 |
d | Day of the month, 2 digits with leading zeros | from 01 to 31 |
D | Abbreviated name of the day of the week, 3 characters | from Mon to Sun |
F | The full month name, such as January or March | January to December |
g | Hours in 12-hour format without leading zeros | 1 to 12 |
G | Hours in 24-hour format without leading zeros | 0 to 23 |
h | Hours in 12-hour format with leading zeros | 01 to 12 |
H | Hours in 24-hour format with leading zeros | 00 to 23 |
i | Minutes with leading zeros | 00 to 59 |
I (capital i) | Daylight saving time sign | 1 if the date is daylight saving time, otherwise 0 otherwise. |
j | Day of the month without leading zeros | 1 to 31 |
l (lowercase "L") | Full name of the day of the week | Sunday to Saturday |
L | Leap year sign | 1 if the year is a leap year, otherwise 0. |
m | The ordinal number of the month with leading zeros | 01 to 12 |
M | Abbreviated name of the month, 3 characters | Jan to Dec |
n | The ordinal number of the month without leading zeros | 1 to 12 |
O | Difference from GMT in hours | For example: +0200 |
r | Date in RFC 2822 format | For example: Thu, 21 Dec 2000 16:01:07 +0200 |
s | Seconds with leading zeros | 00 to 59 |
S | English suffix of ordinal number of the day of the month, 2 characters | st, nd, rd, or th. Used in conjunction with j |
t | Number of days in a month | 28 to 31 |
T | Time zone on the server | Examples: EST, MDT ... |
U | The number of seconds since the beginning of the Unix Epoch (The Unix Epoch, January 1, 1970, 00:00:00 GMT) | see also time () |
w | Sequential day of the week | 0 (Sunday) to 6 (Saturday) |
W | ISO-8601 week ordinal, first day of week is Monday (added in PHP 4.1.0) | For example: 42 (42nd week of the year) |
Y | Sequential number of the year, 4 digits | Examples: 1999, 2003 |
y | Year number, 2 digits | Examples: 99, 03 |
z | The ordinal number of the day in the year (numbered from 0) | 0 to 365 |
Z | Timezone offset in seconds. For time zones west of UTC this is a negative number, east of UTC it is positive. | -43200 to 43200 |
Any other characters encountered in the string format, will be displayed in the resulting line without changes. Z always returns 0 when used gmdate () .
Examples of using the date () function
You can avoid recognizing a character as a formatting character by escaping the character with \. If a special character (for example, \ t) is combined with \, add another \.
Escaping characters in the date () function
The date function exists to display the time or date in a custom format.
This example displays the current date in day / month / year format as numbers. After reading this article to the end, you can display the current date and time in any format.
This function allows you to display not only the current date and time, but also convert the time stamp to a specified format. The timestamp is the number of seconds since linux was founded. This number can be obtained using the time () function. The timestamp in the date function is an optional parameter.To get the format you want, you can use special modifiers in the first parameter. There are a lot of them.
The character in the format string | Description | Return value example |
---|---|---|
a | lowercase am or pm | am, pm |
A | Uppercase AM or PM | AM, PM |
B | Swatch Internet time | 000 to 999 |
c | Date in ISO 8601 format (added in PHP 5) | 2005-06-11T11: 11: 11 + 00: 00 |
d | Day of the month, 2 digits with leading zeros | from 01 to 31 |
D | Abbreviated name of the day of the week, 3 characters | from Mon to Sun |
F | Full month name | January to December |
g | Hours in 12-hour format without leading zeros | 1 to 12 |
G | Hours in 24-hour format without leading zeros | 0 to 23 |
h | Hours in 12-hour format with leading zeros | 01 to 12 |
H | Hours in 24-hour format with leading zeros | 00 to 23 |
i | Minutes with leading zeros | 00 to 59 |
I (capital i) | Daylight saving time sign | 1 if the date is daylight saving time, otherwise 0 otherwise. |
j | Day of the month without leading zeros | 1 to 31 |
l (lowercase "L") | Full name of the day of the week | Sunday to Saturday |
L | Leap year sign | 1 if the year is a leap year, otherwise 0. |
m | The ordinal number of the month with leading zeros | 01 to 12 |
M | Abbreviated name of the month, 3 characters | Jan to Dec |
n | The ordinal number of the month without leading zeros | 1 to 12 |
O | Difference from GMT in hours | +0200 |
r | Date in RFC 2822 format | Thu, 28 Jan 2011 15:11:14 +0200 |
s | Seconds with leading zeros | 00 to 59 |
S | English suffix of ordinal number of the day of the month, 2 characters | st, nd, rd, or th. Used in conjunction with j |
t | Number of days in a month | 28 to 31 |
T | Time zone on the server | Examples: EST, MDT ... |
U | The number of seconds since the beginning of the Unix Epoch (The Unix Epoch, January 1, 1970, 00:00:00 GMT) | 1356361196 |
w | Sequential day of the week | 0 (Sunday) to 6 (Saturday) |
W | ISO-8601 week ordinal, first day of week is Monday (added in PHP 4.1.0) | For example: 42 (42nd week of the year) |
Y | Sequential number of the year, 4 digits | Examples: 1986, 2012 |
y | Year number, 2 digits | Examples: 86, 12 |
z | The ordinal number of the day in the year (numbered from 0) | 0 to 365 |
Z | Timezone offset in seconds. For time zones west of UTC this is a negative number, east of UTC it is positive. | -43200 to 43200 |
If this site was useful to you, you can help in its development by placing
JavaScript is blocked in your browser. Please enable JavaScript for the site to work!
Date and time representation
In distributed systems such as the Internet, time plays a special role. Due to a slight discrepancy in the system clock, a player in the Forex market can lose tens of thousands of dollars in a few minutes; the business intelligence system will make a mistake in forecasting; NNTP servers in the process of synchronization will lose important information needed by the user, etc.
PHP contains many functions for working with date and time. The most commonly used are:
- time ()- returns the current absolute time. This number is equal to the number of seconds that have passed since midnight January 1, 1970 (since the beginning of the UNIX era).
- getdate ()- reads information about date and time. Returns an associative array containing information for the specified time or for the current (by default) time. The array contains the following elements:
Example 1
Using getdate () $ val) echo "$ key = $ val
"; echo"
Today: $ d. $ D. $ D ";?>RESULT OF EXAMPLE 1:
Seconds = 21 minutes = 4 hours = 12 mday = 10 wday = 4 mon = 11 year = 2005 yday = 313 weekday = Thursday month = November 0 = 1131613461 Today: 11/10/2005
- date ()- date and time formatting. Arguments: format string and absolute time. The second argument is optional. Returns a string with the specified or current date in the specified format. The format string can contain the following codes:
a A Included designation "AM" or "PM" d Day of the month (01-31) D Abbreviated name of the day of the week (three letters) F Full month name g Hours (12-hour format without leading zeros) G Hours (24-hour format without leading zeros) h Clock (12 hour format) H Clock (24-hour format) i Minutes (00-59) j Day of the month without leading zeros (1-31) l Full name of the day of the week L Leap year (0 or 1) m Month (01-12) M Abbreviated month name (three letters) n Month (1-12) s Seconds (00-59) t Number of days in a given month (28 to 31) U Absolute time w y Year (two digits) Y Year (four digits) z Day of the year (0-365) Z Time zone offset in seconds (-43200 to 43200) Any other information included in the format string will be inserted into the returned string. If you want to add characters to the format string that are format codes themselves, you must precede them with a backslash "\". Characters that become format codes when added with a backslash must be preceded by two forward slashes. For example, if you want to add "n" to a string, you would enter "\\ n" because "\ n" is a newline character.
Example 2
Using date () RESULT OF EXAMPLE 2:
Today: 10.11.05 13:03
- mktime ()- returns the absolute time, which can then be used with the date () or getdate () functions. Accepts up to six integer arguments in the following order:
Clock
minutes
seconds
month
day of month
yearExample 3
Using mktime () RESULT OF EXAMPLE 3:
- checkdate ()- checking the correctness of the date. Arguments: month, day, year. Returns true if the date is correct, i.e.
month - an integer from 1 to 12;
day is an integer not exceeding the total number of days in a given month. In this case, leap years are handled correctly;
year is an integer from 1 to 32767.For example:
If (! Checkdate ($ month, 1, $ year)) ($ d = getdate (); $ month = $ d; $ year = $ d;)
Attention! The date can be in a valid range, but other date functions will not accept this value. So, you cannot use mktime () for years before 1902, and you should also use it carefully for years before 1970.
- strftime ()- formation of local date and time. Arguments: format string and absolute time. The second argument is optional. Returns a string with the specified or current date in the specified format. In this case, the names of months and days of the week are extracted from the locale selected using the Format string function can contain the following codes:
% a Abbreviated name of the day of the week % A Full name of the day of the week % b Abbreviated month name % B Full month name % c Preferred Date and Time Format % C Century number % d Day of the month (1-31) % D Same as % m /% d /% y % e Month (1-12) % h Same as % b % H Clock (24-hour format) % I Clock (12 hour format) % j Day of the year (0-365) % m Month (1-12) % M Minutes % n Newline character % p The designation "am" or "pm" is included % r Time using a.m./p.m.-notation % R Time in 24-hour format % S Seconds (00-59) % t Tab character % T Same as % H:% M:% S % u Day of the week number (1 - Monday, 7 - Sunday) % U Week number. Countdown starts from the first Sunday of the year % V ISO 8601: 1988 week number. The first week must have at least four days, and Monday is considered the first day % W Week number. Countdown starts from the first Monday of the year % w Day of the week number (0 - Sunday, 6 - Saturday) % x Preferred date format without time % X Preferred time format without date % y Year (two digits) % Y Year (four digits) % Z Time zone (name or abbreviation) %% The "%" character Any other information included in the format string will be inserted into the returned string.
(PHP 4, PHP 5, PHP 7)
date - Formats the output of the system date / time
Description
String date (string $ format [, int $ timestamp = time () ])
Returns a string formatted according to the specified format template. The timestamp specified by the timestamp argument is used, or the current system time if no timestamp is specified. So timestamp is optional and defaults to the value returned by the function time ().
Parameter List
The resulting string template ( string) with a date. See formatting options below. There are also several predefined date / time constants that can be used in place of these parameters. For example: DATE_RSS replaces template "D, d M Y H: i: s".
The character in the format string | Description | Return value example |
---|---|---|
Day | --- | --- |
d | Day of the month, 2 digits with leading zeros | from 01 before 31 |
D | Day of the week text representation, 3 characters | from Mon before Sun |
j | Day of the month without leading zeros | from 1 before 31 |
l(lowercase "L") | Full name of the day of the week | from Sunday before Saturday |
N | The ordinal number of the day of the week according to the ISO-8601 standard (added in PHP 5.1.0) | from 1 (Monday) to 7 (Sunday) |
S | English suffix of ordinal number of the day of the month, 2 characters | st, nd, rd or th... Used in conjunction with j |
w | Sequential day of the week | from 0 (Sunday) to 6 (Saturday) |
z | The ordinal number of the day in the year (starting from 0) | From 0 before 365 |
A week | --- | --- |
W | The ordinal number of the week of the year in accordance with the ISO-8601 standard; weeks start from monday (added in PHP 4.1.0) | For example: 42 (42nd week of the year) |
Month | --- | --- |
F | The full month name, such as January or March | from January before December |
m | The ordinal number of the month with a leading zero | from 01 before 12 |
M | Abbreviated name of the month, 3 characters | from Jan before Dec |
n | The ordinal number of the month without a leading zero | from 1 before 12 |
t | Number of days in the specified month | from 28 before 31 |
Year | --- | --- |
L | Leap year sign | 1 if the year is a leap year, otherwise 0 . |
o | Year number according to ISO-8601 standard. Has the same meaning as Y unless the ISO week number ( W) belongs to the previous or next year; then the year of that week will be used. (added in PHP 5.1.0) | Examples: 1999 or 2003 |
Y | Sequential number of the year, 4 digits | Examples: 1999 , 2003 |
y | Year number, 2 digits | Examples: 99 , 03 |
Time | --- | --- |
a | Ante meridiem (English "before noon") or Post meridiem (English "afternoon") in lower case | am or pm |
A | Ante meridiem or Post meridiem in uppercase | AM or PM |
B | Time in Internet time (alternate time of day) format | from 000 before 999 |
g | Clock in 12-hour format without leading zero | from 1 before 12 |
G | Hours in 24-hour format without leading zeros | from 0 before 23 |
h | Hours in 12-hour format with leading zeros | from 01 before 12 |
H | Hours in 24-hour format with leading zeros | from 00 before 23 |
i | Minutes with leading zeros | from 00 before 59 |
s | Leading zero seconds | from 00 before 59 |
u | Microseconds (added in PHP 5.2.2). Please note that date () will always return 000000 since it takes an integer ( integer) parameter, while DateTime :: format () supports microseconds. | For example: 654321 |
Time zone | --- | --- |
e | Timezone code (added in PHP 5.1.0) | Examples: UTC, GMT, Atlantic / Azores |
I(capital i) | Daylight saving time sign | 1 if the date corresponds to daylight saving time, 0 otherwise. |
O | Difference from GMT, in hours | For example: +0200 |
P | Difference from GMT with colon between hours and minutes (added in PHP 5.1.3) | For example: +02:00 |
T | Timezone abbreviation | Examples: EST, MDT ... |
Z | Timezone offset in seconds. For time zones west of UTC, negative numbers are returned, and times east of UTC are returned positive. | from -43200 before 50400 |
Full date / time | --- | --- |
c | Date in ISO 8601 format (added in PHP 5) | 2004-02-12T15: 19: 21 + 00: 00 |
r | Date in the format "RFC 2822 | For example: Thu, 21 Dec 2000 16:01:07 +0200 |
U | The number of seconds since the beginning of the Unix Epoch (The Unix Epoch, January 1, 1970 00:00:00 GMT) | see also time () |
Any other characters encountered in the wildcard string will be printed to the resulting string unchanged. Z always returns 0 using gmdate ().
timestampComment:
Since the function in question takes as a parameter timestamps of the type integer formatting character u will only be useful when using the function date_format () and custom timestamps created with the function date_create ().
The optional timestamp parameter is integer a timestamp that defaults to the current local time if no timestamp is specified. In other words, the default is the result of the function time ().
Return Values
Returns a formatted date string. If you pass a non-numeric value as a parameter, timestamp will be returned FALSE and a level error is caused E_WARNING.
List of changes
Version | Description |
---|---|
5.1.0 | The valid date range for timestamps is usually between December 13, 1901, 20:45:54 GMT, through January 19, 2038, 03:14:07 GMT. (They correspond to the minimum and maximum value of a 32-bit signed integer.) However, for PHP versions below 5.1.0 on some operating systems (eg Windows), this range was limited to dates 01-01-1970 to 19-01-2038. |
5.1.0 | Timezone errors now generate level errors E_STRICT and E_NOTICE. |
5.1.1 | For standard date / time formats, there are special constants that can be specified as the format parameter. |
Examples of
Example # 1 Examples of using a function date ()
// set the default timezone. Available since PHP 5.1
date_default_timezone_set ("UTC");
// will print something like this: Monday
echo date ("l");
// will output something like this: Monday 8th of August 2005 03:12:46 PM
echo date ("l jS \ of F Y h: i: s A");
// prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a". date ("l", mktime (0, 0, 0, 7, 1, 2000));
/ * an example of using a constant as a formatting parameter * /
// will output something like this: Wed, 25 Sep 2013 15:28:57 -0700
echo date (DATE_RFC2822);
// will output something like this: 2000-07-01T00: 00: 00 + 00: 00
echo date (DATE_ATOM, mktime (0, 0, 0, 7, 1, 2000));
?>
To prevent a character from being recognized as a formatting character, escape it with a backslash. If the escaped character is also a formatting sequence, then it SHOULD be re-escaped.
Example # 2 Escaping characters in a function date ()
// will print something like this: Wednesday the 15th
echo date ("l \ t \ h \ e jS");
?>
To display past and future dates, it is convenient to use the functions date () and mktime ().
Example # 3 Function sharing example date () and mktime ()
$ tomorrow = mktime (0, 0, 0, date ("m"), date ("d") + 1, date ("Y"));
$ lastmonth = mktime (0, 0, 0, date ("m") - 1, date ("d"), date ("Y"));
$ nextyear = mktime (0, 0, 0, date ("m"), date ("d"), date ("Y") + 1);
?>
Comment:
This method is more reliable than simple subtraction and addition of seconds to the timestamp, since it allows you to flexibly switch to summer / winter time if necessary.
A few more examples of using the function date ()... It is important to note that you should escape any characters that need to be left unchanged. This is also true for those characters that are not recognized as formatting characters in the current version of PHP, as this may be introduced in future versions. Single quotes should be used to escape escape sequences (for example, \ n).
Example # 4 Formatting using date ()
// Suppose the current date is March 10, 2001, 5:16:18 PM,
// and we are in the Mountain Standard Time (MST)
$ today = date ("F j, Y, g: i a"); // March 10, 2001, 5:16 pm
$ today = date ("m.d.y"); // 03.10.01
$ today = date ("j, n, Y"); // 10, 3, 2001
$ today = date ("Ymd"); // 20010310
$ today = date ("h-i-s, j-m-y, it is w Day"); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$ today = date ("\ i \ t \ i \ s \ t \ h \ e jS \ d \ a \ y."); // it is the 10th day.
$ today = date ("D M j G: i: s T Y"); // Sat Mar 10 17:16:18 MST 2001
$ today = date ("H: m: s \ m \ i \ s \ \ m \ o \ n \ t \ h"); // 17:03:18 m is month
$ today = date ("H: i: s"); // 17:16:18
$ today = date ("Y-m-d H: i: s"); // 2001-03-10 17:16:18 (MySQL DATETIME format)
?>
To format dates in other languages, use instead date () functions setlocale () and strftime ().
Notes (edit)
Comment:
To get the timestamp from the string representation of the date, you can use the function strtotime ()... In addition, some databases have their own functions for converting the internal date representation to a timestamp (for example, the MySQL »UNIX_TIMESTAMP function).