PHP Date and Time
Dates and times are used in almost every website: show the current date, calculate an age, set an offer end date, or save when a post was created. PHP has simple functions for this, and a powerful DateTime class.
Time zone
PHP uses a time zone to show the right local time. Set it at the start of your script, or in php.ini.
<?php
date_default_timezone_set("Asia/Kolkata");
echo date_default_timezone_get();
?>
Output:
Asia/Kolkata
time() and date()
time() returns the current time as a timestamp, the number of seconds since 1 January 1970. The date() function turns a timestamp into readable text, using format characters.
| Character | Meaning | Example |
|---|---|---|
| d | Day of month, 2 digits | 05 |
| j | Day of month, no zero | 5 |
| D / l | Day name, short / full | Fri / Friday |
| m | Month number | 12 |
| M / F | Month name, short / full | Dec / December |
| Y / y | Year, 4 digits / 2 digits | 2026 / 26 |
| H / h | Hour, 24 hours / 12 hours | 14 / 02 |
| i | Minutes | 07 |
| s | Seconds | 09 |
| A | AM or PM | PM |
<?php
echo date("d M Y", strtotime("2026-12-25")) . "<br>";
echo date("l", strtotime("2026-12-25")) . "<br>";
echo date("Y-m-d H:i:s", 86400);
?>
Output:
25 Dec 2026
Friday
1970-01-02 00:00:00
To show the current date use date("Y-m-d"), because date() without a timestamp uses the current time.
strtotime(), mktime() and checkdate()
<?php
echo date("Y-m-d", strtotime("2026-01-31 +1 day")) . "<br>";
echo date("Y-m-d", mktime(0, 0, 0, 12, 25, 2026)) . "<br>";
var_dump(checkdate(2, 30, 2026));
?>
Output:
2026-02-01
2026-12-25
bool(false)
strtotime()understands English text like “tomorrow”, “next Monday” or “+1 week”.mktime(hour, minute, second, month, day, year)builds a timestamp.checkdate(month, day, year)checks if a date is valid. 30 February is not.
The DateTime class
For modern code use the DateTime class. It is easier for calculations, and it handles time zones better.
<?php
$start = new DateTime("2026-01-01");
$end = new DateTime("2026-03-01");
echo $start->diff($end)->days . " days<br>";
$start->modify("+10 days");
echo $start->format("d F Y");
?>
Output:
59 days
11 January 2026
diff()gives the difference between two dates.modify()adds or subtracts time.format()uses the same characters as date().
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |