Using PHP date() Function to Format Dates and Times
This article explains PHP's date() function, its syntax, required and optional parameters, and provides multiple code examples demonstrating how to retrieve and format current dates, times, and timestamps for various use cases in backend development.
PHP is a widely used server‑side language for web development that provides powerful date and time handling capabilities. The date() function is a commonly used built‑in function that returns the current date and time or a specified timestamp.
The syntax of date() is:
date(format,timestamp)The format argument is required and defines the output format, while the optional timestamp argument specifies a Unix timestamp; if omitted, the current date and time are used.
The following code examples demonstrate various ways to use date() :
";
// 2. Return current date
echo date("Y-m-d");
echo "
";
// 3. Return current time
echo date("H:i:s");
echo "
";
// 4. Return year
echo date("Y");
echo "
";
// 5. Return month
echo date("m");
echo "
";
// 6. Return day
echo date("d");
echo "
";
// 7. Return weekday
echo date("l");
echo "
";
// 8. Use a timestamp to get a specific date and time
$timestamp = mktime(10, 30, 0, 12, 25, 2022);
echo date("Y-m-d H:i:s", $timestamp);
echo "
";
// 9. Convert a date string to a timestamp and format it
$time_str = "2022-12-25 10:30:00";
$timestamp = strtotime($time_str);
echo date("Y-m-d H:i:s", $timestamp);
echo "
";
?>These examples show how different format strings produce outputs such as the full date and time, year, month, day, and weekday.
The date() function supports many format characters; refer to the official PHP documentation for a complete list.
Because date() returns a string, it can be output directly with echo .
In summary, the PHP date() function is a versatile tool for obtaining and formatting date and time information, making it indispensable in web development.
PHP 8, here I come
Scan the QR code to receive free learning materials
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.