How to Get Current Date in PHP: Simple Guide
Use the
date() function in PHP to get the current date. For example, date('Y-m-d') returns the date in year-month-day format like 2024-06-01.Syntax
The date() function formats the current date and time according to the string you provide. The string uses format characters like Y for a 4-digit year, m for month, and d for day.
Example format: date('Y-m-d') returns the date as year-month-day.
php
date(string $format): string
Example
This example shows how to get and print the current date in the format YYYY-MM-DD.
php
<?php // Get current date in year-month-day format $currentDate = date('Y-m-d'); echo "Today's date is: $currentDate"; ?>
Output
Today's date is: 2024-06-01
Common Pitfalls
- Not setting the correct timezone can cause the date to be off. Use
date_default_timezone_set()to set your timezone. - Using wrong format characters will give unexpected results. For example,
mis month,Mis short month name. - Calling
date()without parentheses or quotes around the format string causes errors.
php
<?php // Wrong: missing quotes around format string // echo date(Y-m-d); // Causes error // Correct: quotes around format string echo date('Y-m-d'); // Set timezone to avoid wrong date // date_default_timezone_set('America/New_York');
Quick Reference
| Format Character | Meaning | Example |
|---|---|---|
| Y | 4-digit year | 2024 |
| y | 2-digit year | 24 |
| m | Month with leading zero | 06 |
| n | Month without leading zero | 6 |
| d | Day with leading zero | 01 |
| j | Day without leading zero | 1 |
Key Takeaways
Use the date() function with a format string to get the current date in PHP.
Always set the timezone with date_default_timezone_set() to get accurate dates.
Use correct format characters like 'Y' for year, 'm' for month, and 'd' for day.
Put the format string inside quotes when calling date(), like date('Y-m-d').