Current Location: Home> Latest Articles> How to Use PHP's "date" Function to Format Dates and Times

How to Use PHP's "date" Function to Format Dates and Times

M66 2025-06-20

How to Use PHP's "date" Function to Format Dates and Times

In PHP development, working with dates and times is a common task, especially when dealing with logs, user activities, timestamps, and other time-related functionalities. PHP provides a built-in function, date()

Here, the $format parameter is mandatory and specifies the format in which the date and time should be displayed. The $timestamp parameter is optional, representing a Unix timestamp. If not provided, the current timestamp is used by default.

Common Date and Time Format Codes

Below are some common format codes that can be used to define how dates and times are displayed:

Format Code Description
Y Four-digit year (e.g., 2021)
m Two-digit month (01 to 12)
d Two-digit day of the month (01 to 31)
H 24-hour format of hour (00 to 23)
i Two-digit minute (00 to 59)
s Two-digit second (00 to 59)
a Lowercase am or pm
A Uppercase AM or PM

How to Use the date Function to Format Dates and Times

Here are some common examples showing how to use the date() function to retrieve different formats of date and time:

<?php
// Get the current date and time
$currentDateTime = date("Y-m-d H:i:s");
echo "Current date and time: " . $currentDateTime . "<br>";

// Get the current year
$currentYear = date("Y");
echo "Current year: " . $currentYear . "<br>";

// Get the current month
$currentMonth = date("m");
echo "Current month: " . $currentMonth . "<br>";

// Get the current time (24-hour format)
$currentTime = date("H:i:s");
echo "Current time: " . $currentTime . "<br>";

// Get the current time (12-hour format)
$currentTime12Hr = date("h:i:s a");
echo "Current time (12-hour format): " . $currentTime12Hr . "<br>";

// Get the current date
$currentDate = date("Y-m-d");
echo "Current date: " . $currentDate . "<br>";
?>

These examples show how the date() function can be used to easily retrieve and format various aspects of the current date and time. Whether you need the full date and time, just the year, month, or the specific time, the date() function can handle it effortlessly.

Conclusion

By using PHP's date() function, you can easily format dates and times. Depending on the specific needs of your application, you can select the appropriate format codes to obtain the required date or time information. Mastering the date() function helps you handle time-related operations effectively and flexibly in PHP development.