Current Location: Home> Latest Articles> Comprehensive Guide to PHP Date Formatting with date() Function Examples

Comprehensive Guide to PHP Date Formatting with date() Function Examples

gitbox 2025-08-07

Introduction

In programming, it is often necessary to format dates and times for displaying to users or storing in databases. PHP offers a powerful and convenient function, date(), to format date and time values.

Syntax of date() Function

The date() function is simple to use. The basic syntax is as follows:


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

Here, the $format parameter is required and specifies the output format of the date/time. The optional $timestamp parameter represents a Unix timestamp to format a specific date/time. If omitted, the current time is used.

Details of the $format Parameter

The $format parameter defines how the date and time should be displayed. Common format characters include:

- Y : Four-digit year, e.g., "2022"

- m : Two-digit month, from "01" to "12"

- d : Two-digit day of the month, from "01" to "31"

- H : Hour in 24-hour format, from "00" to "23"

- i : Two-digit minutes, from "00" to "59"

- s : Two-digit seconds, from "00" to "59"

These format characters can be combined flexibly to meet various date and time display requirements.

Examples

Display Current Date and Time


$date = date("Y-m-d H:i:s");
echo $date;  // Outputs something like "2022-01-01 12:34:56"

This code uses the format "Y-m-d H:i:s" to output the current date and time as "year-month-day hour:minute:second".

Format a Specific Date and Time


$timestamp = strtotime("2022-01-01 12:34:56");
$date = date("Y-m-d H:i:s", $timestamp);
echo $date;  // Outputs "2022-01-01 12:34:56"

In this example, the strtotime() function converts the string to a timestamp, which is then formatted by date().

Summary

With the date() function and its format characters explained here, developers can easily handle various date and time formatting needs. Mastering date() enhances user experience and data readability on websites.

References

- PHP Official Documentation - date() Function

- PHP Official Documentation - strtotime() Function