How to Format Date in PHP: Simple Guide with Examples
In PHP, you format dates using the
date() function by passing a format string that defines how the date should appear. For example, date('Y-m-d') outputs the date as year-month-day like 2024-06-01.Syntax
The date() function formats a local date and time, returning it as a string. It takes two parameters:
- format (string): Specifies the output format using characters like
Yfor full year,mfor month,dfor day, etc. - timestamp (optional integer): A Unix timestamp to format. If omitted, the current date and time is used.
php
string date(string $format, int|null $timestamp = null)
Example
This example shows how to format the current date as year-month-day and a custom timestamp as a readable date and time.
php
<?php // Format current date as YYYY-MM-DD echo date('Y-m-d') . "\n"; // Format a specific timestamp (e.g., 1st Jan 2020 15:30:00) $timestamp = mktime(15, 30, 0, 1, 1, 2020); echo date('l, F j, Y H:i:s', $timestamp); ?>
Output
2024-06-01
Wednesday, January 1, 2020 15:30:00
Common Pitfalls
Common mistakes include:
- Using incorrect format characters (e.g.,
MMinstead ofmfor month). - Not providing a timestamp when formatting a specific date, which defaults to the current date.
- Confusing
date()withstrtotime()which parses strings into timestamps.
php
<?php // Wrong: 'MM' is not a valid format for month // echo date('YYYY-MM-DD'); // Incorrect // Right: echo date('Y-m-d'); // Correct ?>
Output
2024-06-01
Quick Reference
| Format Character | Meaning | Example Output |
|---|---|---|
| Y | 4-digit year | 2024 |
| y | 2-digit year | 24 |
| m | 2-digit month (01-12) | 06 |
| n | Month without leading zero (1-12) | 6 |
| d | 2-digit day (01-31) | 01 |
| j | Day without leading zero (1-31) | 1 |
| H | 24-hour format (00-23) | 15 |
| h | 12-hour format (01-12) | 03 |
| i | Minutes with leading zero (00-59) | 30 |
| s | Seconds with leading zero (00-59) | 00 |
| l | Full weekday name | Wednesday |
| F | Full month name | January |
Key Takeaways
Use the date() function with a format string to display dates in PHP.
Remember to use correct format characters like Y for year, m for month, and d for day.
If no timestamp is given, date() returns the current date and time.
Avoid common mistakes like using uppercase MM for month; use lowercase m instead.
Use mktime() or strtotime() to create timestamps for formatting specific dates.