PHP › Date & Time Handling

How do you format a date or time value in PHP using the format method, and what do common format characters like Y, m, and d represent?

Beginner

Answer

The format method on a DateTime object accepts a format string made up of special characters that each represent a specific piece of the date or time, such as uppercase Y for a four digit year, lowercase m for a two digit month, and lowercase d for a two digit day, letting you produce a date string in virtually any layout your application needs simply by combining these characters in the desired order.
$date = new DateTime();
echo $date->format('Y-m-d');
echo $date->format('l, F j, Y');
Real-world example An invoice generation system formats the invoice date as a full readable format like Monday, September seventh, 2026 for the printed invoice, while storing the same date internally in the database using the compact year month day format.

Common follow-ups: What is the difference between the lowercase and uppercase versions of the month format character?;How do you display a date in a specific format based on the user's locale?