What is the date()
function in PHP?
The date()
function in PHP formats a local date and time.
It returns a string formatted according to the given format.
Basic Syntax:
date(string $format, int $timestamp = time()): string
$format
→ How you want your date/time to look.$timestamp
→ (optional) Unix timestamp (seconds since 1970-01-01 00:00:00 UTC).
If not given, it uses the current date and time.
Common Date Formats
Format | Meaning | Example Output |
---|---|---|
d |
Day (2 digits) | 01 to 31 |
m |
Month (2 digits) | 01 to 12 |
Y |
Year (4 digits) | 2025 |
y |
Year (2 digits) | 25 |
H |
Hour (24-hour) | 00 to 23 |
h |
Hour (12-hour) | 01 to 12 |
i |
Minutes | 00 to 59 |
s |
Seconds | 00 to 59 |
A |
AM or PM | AM or PM |
l |
Full weekday name | Monday, etc. |
F |
Full month name | January, etc. |
Examples
1. Display Current Date
echo date("Y-m-d");
// Output: 2025-04-27
2. Display Current Date and Time
echo date("Y-m-d H:i:s");
// Output: 2025-04-27 14:45:10
3. Display Day and Month Name
echo date("l, F jS Y");
// Output: Sunday, April 27th 2025
4. Specific Timestamp Formatting
$timestamp = strtotime("2025-01-01");
echo date("d-m-Y", $timestamp);
// Output: 01-01-2025
5. Custom Time with AM/PM
echo date("h:i A");
// Output: 02:45 PM
Bonus: Setting Timezone
If you want dates based on a specific timezone:
date_default_timezone_set("Asia/Kolkata");
echo date("Y-m-d H:i:s");
// Output (India Time): 2025-04-27 20:15:30
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.