Handling dates and times is a core part of web development, whether for displaying post dates, scheduling tasks, or recording transaction times. PHP's date() function is the primary tool for formatting local dates and times.
date() FunctionThe date() function formats a local date and time, and returns the formatted date string.
Syntax: date(format, timestamp)
d - Represents the day of the month (01 to 31)m - Represents a month (01 to 12)Y - Represents a year (in four digits)l (lowercase 'L') - Represents the day of the week<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l"); // e.g: Monday
?>
You can also format time using the following characters:
h - 12-hour format of an hour (01 to 12)i - Minutes with leading zeros (00 to 59)s - Seconds with leading zeros (00 to 59)a - Lowercase Ante meridiem and Post meridiem (am or pm)<?php
echo "The time is " . date("h:i:sa");
?>
By default, the time returned by date() depends on the server's configuration. To get the time for a specific location, you must set the timezone.
<?php
date_default_timezone_set("Asia/Dhaka");
echo "The time in Dhaka is " . date("h:i:sa");
?>
© 2020-<?php echo date("Y");?> to keep your footer copyright years always up to date automatically!
| Char | Description | Example |
|---|---|---|
Y | Year (4 digits) | 2024 |
M | Short Month name | Jan |
d | Day (01-31) | 17 |
H | 24-hour format | 14 |
i | Minutes | 05 |