PHP - PHP Date and Time Handling
PHP provides powerful built-in features for working with dates, times, time zones, durations, and date calculations. Date and time handling is important in applications such as booking systems, attendance systems, billing software, event management, scheduling applications, reporting systems, and websites that display information based on the current date or time.
PHP mainly provides date and time functionality through functions such as date(), time(), strtotime(), and the object-oriented DateTime and DateTimeImmutable classes.
1. Getting the Current Date
The date() function can be used to format the current date.
<?php
echo date("Y-m-d");
?>
Output:
2026-09-17
Here:
-
Yrepresents a four-digit year. -
mrepresents the month with leading zero. -
drepresents the day with leading zero.
For example, the following format displays the date differently:
echo date("d/m/Y");
Output:
17/09/2026
2. Getting the Current Time
PHP's date() function can also display the current time.
<?php
echo date("H:i:s");
?>
Output:
14:35:20
The format characters are:
-
H– 24-hour format -
i– minutes -
s– seconds
For a 12-hour clock:
echo date("h:i:s A");
Possible output:
02:35:20 PM
Here, A displays AM or PM.
3. Understanding Unix Timestamps
A Unix timestamp represents the number of seconds elapsed since January 1, 1970, UTC.
PHP provides the time() function to obtain the current Unix timestamp.
<?php
echo time();
?>
A timestamp might look like:
1789655720
Timestamps are useful when comparing dates and times or calculating the difference between two points in time.
For example:
$start = time();
// Some operation
$end = time();
$duration = $end - $start;
echo "Operation took $duration seconds.";
4. Creating a DateTime Object
For more advanced date and time operations, PHP provides the DateTime class.
<?php
$date = new DateTime();
echo $date->format("Y-m-d H:i:s");
?>
The DateTime object represents a specific date and time and provides methods for formatting and modifying that value.
A specific date can also be created:
$date = new DateTime("2026-09-17");
echo $date->format("d-m-Y");
Output:
17-09-2026
5. Formatting Dates with DateTime
The format() method controls how a date is displayed.
<?php
$date = new DateTime("2026-09-17 15:30:45");
echo $date->format("d/m/Y");
echo "<br>";
echo $date->format("H:i:s");
echo "<br>";
echo $date->format("l, F j, Y");
?>
Possible output:
17/09/2026
15:30:45
Thursday, September 17, 2026
Common formatting characters include:
| Format | Meaning |
|---|---|
Y |
Four-digit year |
y |
Two-digit year |
m |
Numeric month |
M |
Short month name |
F |
Full month name |
d |
Day with leading zero |
j |
Day without leading zero |
D |
Short weekday name |
l |
Full weekday name |
H |
24-hour hour |
h |
12-hour hour |
i |
Minutes |
s |
Seconds |
A |
AM or PM |
6. Modifying Dates
The modify() method allows a date to be changed.
<?php
$date = new DateTime("2026-09-17");
$date->modify("+5 days");
echo $date->format("Y-m-d");
?>
Output:
2026-09-22
You can also subtract time:
$date->modify("-2 months");
Other examples include:
$date->modify("+1 year");
$date->modify("+3 weeks");
$date->modify("-10 days");
This is useful when applications need to calculate deadlines, renewal dates, delivery dates, or appointment dates.
7. Using DateInterval
DateInterval represents a period of time.
For example:
<?php
$interval = new DateInterval("P10D");
echo $interval->d;
?>
Here, P10D means a period of 10 days.
A period of two years, three months, and five days can be represented as:
P2Y3M5D
The basic structure is:
P [years] [months] [days]
Time components can also be included. For example:
PT5H30M
represents 5 hours and 30 minutes.
8. Calculating the Difference Between Dates
PHP provides the diff() method for calculating the difference between two dates.
<?php
$start = new DateTime("2026-09-01");
$end = new DateTime("2026-09-17");
$difference = $start->diff($end);
echo $difference->days;
?>
Output:
16
The days property represents the total number of days between the two dates.
You can also access individual components:
echo $difference->y;
echo $difference->m;
echo $difference->d;
This can be useful for calculating someone's age, subscription duration, employment duration, or the number of days remaining before an event.
9. Calculating Age
A person's age can be calculated using diff().
<?php
$birthDate = new DateTime("2000-05-15");
$today = new DateTime();
$age = $birthDate->diff($today)->y;
echo "Age: " . $age;
?>
The y property contains the number of complete years.
This method is generally more reliable than simply subtracting the birth year from the current year because it also considers whether the person's birthday has occurred in the current year.
10. DateTimeImmutable
PHP also provides the DateTimeImmutable class.
The important difference between DateTime and DateTimeImmutable is how modifications are handled.
With DateTime, modifying the object changes the original object:
$date = new DateTime("2026-09-17");
$date->modify("+1 day");
echo $date->format("Y-m-d");
The original object now represents September 18.
With DateTimeImmutable:
$date = new DateTimeImmutable("2026-09-17");
$newDate = $date->modify("+1 day");
echo $date->format("Y-m-d");
echo "<br>";
echo $newDate->format("Y-m-d");
Output:
2026-09-17
2026-09-18
The original $date remains unchanged.
This makes DateTimeImmutable useful when predictable, non-mutating date values are desirable.
11. Working with Time Zones
Different parts of the world use different time zones. PHP allows developers to explicitly specify a time zone.
<?php
$date = new DateTime("now", new DateTimeZone("Asia/Kolkata"));
echo $date->format("Y-m-d H:i:s");
?>
Asia/Kolkata represents Indian Standard Time.
Other examples include:
America/New_York
Europe/London
Asia/Tokyo
Australia/Sydney
Using an explicit time zone is especially important for applications serving users from multiple countries.
12. Changing a Time Zone
An existing DateTime object can be converted to another time zone.
<?php
$date = new DateTime(
"2026-09-17 10:00:00",
new DateTimeZone("Asia/Kolkata")
);
$date->setTimezone(new DateTimeZone("America/New_York"));
echo $date->format("Y-m-d H:i:s");
?>
The actual point in time remains the same, but the displayed local time changes according to the destination time zone.
13. Parsing Human-Readable Dates with strtotime()
The strtotime() function converts an English textual date or time description into a Unix timestamp.
<?php
$timestamp = strtotime("2026-09-17");
echo date("Y-m-d", $timestamp);
?>
It can also understand relative expressions:
echo date("Y-m-d", strtotime("+7 days"));
Other examples include:
strtotime("tomorrow");
strtotime("next Monday");
strtotime("+2 months");
strtotime("-1 week");
Although strtotime() is convenient, DateTime and related classes are generally preferable when an application requires more structured date and time manipulation.
14. Creating Dates from a Specific Format
The DateTime::createFromFormat() method is useful when input follows a particular format.
Suppose a user enters:
17/09/2026
The format can be specified explicitly:
<?php
$date = DateTime::createFromFormat("d/m/Y", "17/09/2026");
echo $date->format("Y-m-d");
?>
Output:
2026-09-17
This is particularly useful when processing dates submitted through forms.
15. Validating Date Input
When accepting dates from users, the application should validate them before using them.
For example:
<?php
$date = DateTime::createFromFormat("d/m/Y", "17/09/2026");
$errors = DateTime::getLastErrors();
if ($date && ($errors === false || ($errors['warning_count'] === 0 && $errors['error_count'] === 0))) {
echo "Valid date";
} else {
echo "Invalid date";
}
?>
Validation helps prevent incorrect dates from being stored or processed.
16. Comparing Dates
Date objects can be compared using comparison operators.
<?php
$date1 = new DateTime("2026-09-10");
$date2 = new DateTime("2026-09-17");
if ($date1 < $date2) {
echo "Date 1 is earlier than Date 2";
}
?>
This can be used for checking:
-
Whether a deadline has passed
-
Whether an appointment is upcoming
-
Whether a subscription has expired
-
Whether an event is within a particular period
17. Adding and Subtracting Time Intervals
Instead of using modify(), DateInterval can be used with add() and sub().
<?php
$date = new DateTime("2026-09-17");
$interval = new DateInterval("P30D");
$date->add($interval);
echo $date->format("Y-m-d");
?>
The date is moved forward by 30 days.
To subtract the interval:
$date->sub($interval);
This approach is useful when the same interval needs to be reused.
18. Practical Example: Subscription Expiry
Consider a website where a user purchases a 30-day subscription.
<?php
$purchaseDate = new DateTime("2026-09-17");
$expiryDate = clone $purchaseDate;
$expiryDate->modify("+30 days");
echo "Purchase Date: " . $purchaseDate->format("d-m-Y");
echo "<br>";
echo "Expiry Date: " . $expiryDate->format("d-m-Y");
?>
The application can then compare the expiry date with the current date to determine whether the subscription is still active.
19. Practical Example: Event Countdown
PHP can calculate the number of days remaining before an event.
<?php
$today = new DateTime();
$eventDate = new DateTime("2026-12-25");
$difference = $today->diff($eventDate);
echo $difference->days . " days remaining";
?>
This technique can be used for:
-
Conferences
-
Examinations
-
Product launches
-
Weddings
-
Festivals
-
Registration deadlines
20. Best Practices for PHP Date and Time Handling
When working with dates and times in PHP, several practices make applications more reliable.
First, use an explicit time zone instead of depending on the server's default configuration when the application's time zone matters.
Second, prefer DateTime or DateTimeImmutable for complex date operations instead of manually manipulating date strings.
Third, validate dates received from users before storing or processing them.
Fourth, use a consistent date format for storing data. Databases commonly use formats such as:
YYYY-MM-DD
for dates and:
YYYY-MM-DD HH:MM:SS
for date-time values.
Fifth, be careful when working with users from different time zones. A date such as "September 17" can correspond to different local times depending on where the user is located.
Finally, DateTimeImmutable can be useful when you want date calculations to create new values without accidentally modifying the original date.
Conclusion
PHP's date and time features allow developers to perform much more than simply displaying the current date. Applications can create and format dates, calculate differences, add or subtract periods, work with time zones, validate user-provided dates, compare dates, and manage recurring or deadline-based events.
The most important classes and functions to understand are DateTime, DateTimeImmutable, DateInterval, DateTimeZone, date(), time(), and strtotime(). Together, they provide the foundation for handling dates and times reliably in PHP applications.