In PHP, formatting dates and times is a common task when handling time-related data. By defining different format strings, you can easily control how time is displayed. The most commonly used function is date(), but strftime() and DateTime::format() also offer flexible formatting options.
The date() function outputs time according to a specified format string. Typically, you pass a timestamp as an argument and define the desired format, for example:
echo date("Y-m-d H:i:s", $timestamp); // Example output: 2023-03-08 15:30:59In this example, the format Y-m-d H:i:s displays time as “year-month-day hour:minute:second”.
| Specifier | Description |
|---|---|
| Y | Four-digit year, e.g. 2025 |
| m | Month (two digits) |
| d | Day (two digits) |
| H | Hour (24-hour format) |
| i | Minutes |
| s | Seconds |
The strftime() function is another way to format time, using Unix-style format specifiers:
echo strftime("%Y-%m-%d %H:%M:%S", $timestamp);Compared to date(), strftime() is more suitable for localized date and time formats, especially when you need to display weekday or month names.
In object-oriented programming, you can use the DateTime class to manage and format dates:
$date = new DateTime();
echo $date->format("Y-m-d H:i:s");This method is particularly useful when you need to perform date calculations, such as adding days, months, or converting between time zones.
Whether you use date(), strftime(), or DateTime::format(), PHP provides flexible options for formatting time. Choosing the right method based on your project’s needs ensures consistent, readable, and localized date and time output.