How to Use Date Function in PHP: Syntax and Examples
In PHP, use the
date() function to format the current date and time or a timestamp. You provide a format string to specify how the date should appear, like date('Y-m-d') for year-month-day format.Syntax
The date() function formats a date or time according to the format string you provide. It takes two parameters:
- format (required): A string that defines how the date/time should be formatted using special characters.
- timestamp (optional): An integer Unix timestamp to format. If omitted, the current date/time is used.
Example format characters include Y for a 4-digit year, m for month, and d for day.
php
string date(string $format, int $timestamp = null)
Example
This example shows how to get the current date in Year-Month-Day format and how to format a specific timestamp.
php
<?php // Current date in Y-m-d format echo date('Y-m-d') . "\n"; // Format a specific timestamp (e.g., 1 Jan 2020) echo date('l, F j, Y', 1577836800) . "\n"; ?>
Output
2024-06-14
Wednesday, January 1, 2020
Common Pitfalls
Common mistakes when using date() include:
- Forgetting that the format string is case-sensitive, so
mmeans month, butMmeans short month name. - Not providing a timestamp when you want to format a date other than the current time.
- Using incorrect format characters that produce unexpected results.
Always check the PHP manual for correct format characters.
php
<?php // Wrong: Using uppercase M for month number // echo date('Y-M-d'); // Outputs year, short month name, day // Right: Use lowercase m for month number // echo date('Y-m-d'); ?>
Quick Reference
| Format Character | Meaning | Example Output |
|---|---|---|
| Y | 4-digit year | 2024 |
| y | 2-digit year | 24 |
| m | 2-digit month | 06 |
| n | Month without leading zero | 6 |
| d | 2-digit day | 14 |
| j | Day without leading zero | 14 |
| H | 24-hour format | 15 |
| h | 12-hour format | 03 |
| i | Minutes with leading zeros | 07 |
| s | Seconds with leading zeros | 09 |
| l | Full weekday name | Friday |
| D | Short weekday name | Fri |
Key Takeaways
Use the date() function with a format string to display dates in PHP.
The format string is case-sensitive and controls how the date appears.
If no timestamp is given, date() uses the current date and time.
Check PHP documentation for correct format characters to avoid errors.
Use timestamps to format dates other than the current moment.