Home  >  Article  >  Backend Development  >  Format date and time using PHP function "date"

Format date and time using PHP function "date"

WBOY
WBOYOriginal
2023-07-25 17:36:20964browse

Use PHP function "date" to format date and time

In PHP development, it is often necessary to handle date and time related operations. PHP provides a very useful function "date" to format dates and times.

The basic syntax of the date function is as follows:

string date ( string $format [, int $timestamp = time() ] )

Among them, the $format parameter is required , used to define the format of date and time. The $timestamp parameter is optional and represents a Unix timestamp. If not provided, the current timestamp is used by default.

Here are some commonly used date and time format codes:

Code | Description

Y | Four-digit year (for example: 2021)
m | Two Month represented by digits (01 to 12)
d | Date represented by two digits (01 to 31)
H | Hour in 24-hour format (00 to 23)
i | Two digits The number of minutes represented (00 to 59)
s | The two-digit number of seconds represented (00 to 59)
a | Lowercase am or pm
A | Uppercase AM or PM

The following is some sample code to demonstrate how to use the date function to format date and time:

// 获取当前日期和时间
$currentDateTime = date("Y-m-d H:i:s");
echo "当前日期和时间:" . $currentDateTime . "<br>";

// 获取当前年份
$currentYear = date("Y");
echo "当前年份:" . $currentYear . "<br>";

// 获取当前月份
$currentMonth = date("m");
echo "当前月份:" . $currentMonth . "<br>";

// 获取当前时间(24小时制)
$currentTime = date("H:i:s");
echo "当前时间:" . $currentTime . "<br>";

// 获取当前时间(12小时制)
$currentTime12Hr = date("h:i:s a");
echo "当前时间(12小时制):" . $currentTime12Hr . "<br>";

// 获取当前日期
$currentDate = date("Y-m-d");
echo "当前日期:" . $currentDate . "<br>";

In the above code, we first use the date function to obtain the current date and time, and then obtain it through different format codes Specific information such as year, month, time, etc., and finally output the results to the screen.

Using the date function can achieve very flexible and precise date and time formatting. For different development needs, you can flexibly choose different format codes.

Summary

Using the PHP function "date" can easily format dates and times. Through the reasonable use of different format codes, various development needs can be met. In actual development, you can select the appropriate format code according to specific needs to obtain the required date and time information.

The above is the detailed content of Format date and time using PHP function "date". For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn