Home > Article > Backend Development > PHP time operation date() function
As a commonly used server-side scripting language, PHP is widely used in many web development projects. During the development process, we sometimes need to operate date and time, such as getting the current date, formatting the date and time into a specified format, etc. The date() function provided in PHP is one of the commonly used functions to implement these tasks.
The date() function is a function used to format dates and times in PHP. Its basic syntax is as follows:
string date ( string $format [, int $timestamp = time() ] )
Among them, $format
is the formatted date and The time string can contain various characters and is used to specify the output format of date and time; $timestamp
is an optional parameter, indicating the timestamp to be formatted. If this parameter is not provided, it defaults to the current time.
The following is a brief introduction to some commonly used formatting characters in $format
:
Y
: four-digit yearm
: Month (01-12) d
: Date (01-31) H
: Hour in 24-hour format (00-23) i
: Minutes (00-59) s
: Seconds (00- 59) w
: The numerical representation of the day of the week (0 represents Sunday, 1 represents Monday, and so on) D
: The day of the week Abbreviation of (for example: Mon, Tue, etc.) F
: Full English name of the month (for example, January, February, etc.) j
: Date ( 1-31) By combining the above formatting characters, we can create various date and time formats. For example:
echo date("Y-m-d H:i:s"); // 输出当前的日期和时间,格式为:2022-01-01 12:00:00
In addition, we can specify the date and time by setting the $timestamp
parameter.
$timestamp = strtotime("2022-01-01 00:00:00"); // 将字符串转换为时间戳 echo date("Y-m-d H:i:s", $timestamp); // 输出指定日期和时间,格式为:2022-01-01 00:00:00
Of course, in addition to the formatting characters introduced above, the date() function also supports many other formatting control characters, which can be set differently according to different needs. For example, we can use the L
command to determine whether it is a leap year:
if(date("L") == "1"){ echo "今年是闰年"; } else { echo "今年不是闰年"; }
In addition, PHP also provides some time-related functions, such as strtotime(), time() , mktime(), etc. These functions are also common functions for manipulating date and time.
In short, for PHP time operations, the date() function is very important and commonly used. As long as we master its basic usage and formatting characters, we can easily operate date and time and improve development efficiency.
The above is the detailed content of PHP time operation date() function. For more information, please follow other related articles on the PHP Chinese website!