Using PHP date() Function to Format Dates and Times
This article explains PHP's date() function, detailing its syntax, parameters, common format codes, and provides example code snippets demonstrating how to retrieve and format the current date, time, year, month, and more for flexible date-time handling in backend development.
In PHP development, handling dates and times is a frequent requirement, and the built‑in date() function offers a convenient way to format them.
The basic syntax is:
string date ( string $format [, int $timestamp = time() ] )The $format argument is mandatory and defines the output pattern, while the optional $timestamp argument represents a Unix timestamp; if omitted, the current time is used.
Common format characters include:
代码 | 描述
Y | 四位数的年份(例如:2021)
m | 两位数表示的月份(01 到 12)
d | 两位数表示的日期(01 到 31)
H | 24小时制的小时数(00 到 23)
i | 两位数表示的分钟数(00 到 59)
s | 两位数表示的秒数(00 到 59)
a | 小写的 am 或 pm
A | 大写的 AM 或 PMExample code demonstrates how to use date() to obtain various pieces of date‑time information:
// 获取当前日期和时间
$currentDateTime = date("Y-m-d H:i:s");
echo "当前日期和时间:" . $currentDateTime . "
";
// 获取当前年份
$currentYear = date("Y");
echo "当前年份:" . $currentYear . "
";
// 获取当前月份
$currentMonth = date("m");
echo "当前月份:" . $currentMonth . "
";
// 获取当前时间(24小时制)
$currentTime = date("H:i:s");
echo "当前时间:" . $currentTime . "
";
// 获取当前时间(12小时制)
$currentTime12Hr = date("h:i:s a");
echo "当前时间(12小时制):" . $currentTime12Hr . "
";
// 获取当前日期
$currentDate = date("Y-m-d");
echo "当前日期:" . $currentDate . "
";The script first calls date() to get the current timestamp, then formats it according to different patterns to extract the year, month, time in 24‑hour and 12‑hour formats, and the date, finally outputting each result.
Using the date() function provides flexible and precise date‑time formatting, allowing developers to choose appropriate format codes to meet various backend development needs.
Summary: PHP’s date() function enables easy and accurate formatting of dates and times; by selecting suitable format characters, developers can satisfy a wide range of application requirements.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.