Dates look simple until a project depends on them. An invoice needs a due date fourteen days after issue. A booking system must reject dates in the past. A report has to show a friendly format like 5 November 2026 instead of a raw database value. PHP gives you two main ways to handle this work: the older date and strtotime functions, and the DateTime classes. For new code, DateTime and DateTimeImmutable are the better default because they handle timezones, intervals and comparisons in a readable, object based way.
This guide walks through the everyday jobs: formatting output, creating dates from strings, adding and subtracting days, comparing two dates, finding the difference between them, and working safely with timezones. The same patterns appear across plain PHP sites and WordPress projects, including the templates discussed in registering a custom post type in WordPress, where event and portfolio dates often need custom display.
Formatting Dates with date()
The date function takes a format string and an optional timestamp. If you leave out the timestamp, it uses the current time. The format string is built from single characters, each standing for one part of the date or time.
echo date('Y-m-d'); // 2026-11-05
echo date('d/m/Y'); // 05/11/2026
echo date('j F Y'); // 5 November 2026
echo date('l, j F Y'); // Thursday, 5 November 2026
echo date('H:i'); // 14:30
echo date('h:i A'); // 02:30 PM
echo date('Y-m-d H:i:s'); // 2026-11-05 14:30:00
Y prints a four digit year, m prints a two digit month with a leading zero, and d does the same for the day. Using j instead of d removes the leading zero for the day, and F prints the full month name while M prints the short version. For time, H is the hour in twenty four hour format, h is twelve hour format, i is minutes, s is seconds, and A prints AM or PM. Characters that are not format codes, such as dashes, slashes, spaces and commas, are printed as they are, which is how you build readable patterns. Be careful with letters in literal words inside the format, because many letters have a meaning; that is one reason developers usually keep formats to separators only.
The database friendly pattern Y-m-d H:i:s is worth memorising. It sorts correctly as text, it matches the MySQL DATETIME format, and it avoids the day and month order confusion that affects formats like d/m/Y versus m/d/Y when data moves between systems.
Creating Dates with DateTime
The DateTime class represents a moment in time as an object. You can create one for now, or pass a string that PHP can understand, then format it with the format method, which uses the same characters as date.
$now = new DateTime();
echo $now->format('Y-m-d H:i:s');
$date = new DateTime('2026-11-05');
echo $date->format('l, j F Y'); // Thursday, 5 November 2026
$fromUser = DateTime::createFromFormat('d/m/Y', '05/11/2026');
echo $fromUser->format('Y-m-d'); // 2026-11-05
The first block creates the current moment. The second parses a plain date string. The third block is the important one for real applications: createFromFormat tells PHP exactly which format the incoming string uses, so a value typed as day, month, year is never misread as month, day, year. Always use createFromFormat when the input format is known, such as values from a form or a file. Check its return value too, because it returns false when the string does not match the format, and calling format on false will cause an error. This careful parsing pairs well with the validation habits covered in PHP form handling basics.
Adding and Subtracting Days
Date arithmetic is where DateTime clearly beats manual timestamp maths. Adding 86400 seconds per day breaks around daylight saving changes, while DateInterval understands calendar days properly.
$invoiceDate = new DateTime('2026-11-05');
$dueDate = clone $invoiceDate;
$dueDate->modify('+14 days');
echo $dueDate->format('Y-m-d'); // 2026-11-19
$start = new DateTime('2026-11-05');
$start->add(new DateInterval('P7D'));
echo $start->format('Y-m-d'); // 2026-11-12
$deadline = new DateTime('2026-11-05');
$deadline->sub(new DateInterval('P3D'));
echo $deadline->format('Y-m-d'); // 2026-11-02
The modify method accepts plain phrases such as +14 days, -2 weeks, +1 month or next Monday, which makes one off adjustments easy to read. The add and sub methods take a DateInterval. In the interval string, P starts the period, and D, W, M and Y stand for days, weeks, months and years, so P7D means seven days and P1M means one month. A T in the middle separates date parts from time parts, so PT2H means two hours. Note that modify and add change the object itself. The clone in the invoice example keeps the original issue date untouched while the due date moves forward, a small habit that prevents confusing bugs where one variable silently changes another.
Prefer DateTimeImmutable for Shared Dates
DateTimeImmutable works like DateTime, except its methods return a new object instead of changing the original. For dates that are passed around a codebase, such as an event start date used by several functions, the immutable version is safer because no distant function can alter the value by accident. The method names and format characters are the same, so switching is painless: create the object once as immutable, and treat every modify or add result as a new variable.
Comparing Dates
DateTime objects can be compared directly with the normal comparison operators, which is far clearer than converting everything to timestamps by hand. PHP compares the moment each object represents, including its timezone.
$eventDate = new DateTime('2026-11-20');
$today = new DateTime('today');
if ($eventDate < $today) {
echo 'This event has already passed.';
} elseif ($eventDate == $today) {
echo 'This event is today.';
} else {
echo 'This event is in the future.';
}
$expiry = new DateTime('+30 days');
if ($expiry > new DateTime()) {
echo 'Still valid.';
}
Creating a DateTime with the word today gives midnight at the start of the current day, which is usually what date only comparisons need. Without that, a DateTime created with no time defaults in ways that can surprise you, and comparing a date with a time against a date without one can put an event on the wrong side of the boundary. Decide whether your comparison is about a calendar day or an exact moment, then create both sides in the same way. For expiry checks, licence checks and booking cut offs, these few lines cover most real requirements.
Finding the Difference Between Two Dates
The diff method returns a DateInterval describing the gap between two dates. From that object you can read total days, or the separate year, month and day parts.
$start = new DateTime('2026-11-05');
$end = new DateTime('2026-12-24');
$diff = $start->diff($end);
echo $diff->days; // 49
echo $diff->format('%m months and %d days');
The days property gives the total number of full days between the two moments, which is what countdowns, trial periods and rental durations usually need. The format method on the interval uses percent signs before its codes, unlike date formatting, so %d means the day component of the interval rather than a calendar day. One caution: the month and day components depend on the calendar, so a gap of one month and five days is not always thirty five days. When a single number matters, use the total days value. When a human friendly phrase matters, use the parts.
Working with Timezones
Servers, databases and users are often in different timezones, and ignoring that fact is the root of many off by a few hours bugs. PHP has a default timezone, usually set in php.ini, and you can set it in code for a script. More importantly, each DateTime object carries its own timezone.
date_default_timezone_set('Asia/Karachi');
$utc = new DateTime('2026-11-05 12:00:00', new DateTimeZone('UTC'));
$local = clone $utc;
$local->setTimezone(new DateTimeZone('Asia/Karachi'));
echo $local->format('Y-m-d H:i:s'); // 2026-11-05 17:00:00
The example creates a moment at noon UTC, then converts a copy of it to Karachi time, which is five hours ahead, producing five in the afternoon. The moment itself has not changed, only how it is displayed. A reliable rule for applications is to store times in UTC in the database, then convert to the user’s timezone only for display. That rule keeps sorting, comparisons and differences correct, and it avoids the mess that follows when stored values are a mixture of local times from different places. When you send date based messages, such as reminders, the conversion also decides whether a notification lands at a sensible local hour, which connects neatly with the delivery topics in sending email in PHP.
Common Date Mistakes to Avoid
A few errors show up repeatedly in code reviews. The first is trusting strtotime with ambiguous strings: a value like 05/11/2026 is read differently depending on separators and locale assumptions, so prefer createFromFormat for known inputs. The second is doing arithmetic in seconds instead of calendar units, which fails around daylight saving transitions. The third is comparing formatted strings instead of objects; strings in day first order do not sort or compare correctly. The fourth is forgetting that DateTime is mutable, then wondering why a start date moved after being passed to a helper function. Using DateTimeImmutable or cloning at the right moment solves that cleanly.
Also watch month end arithmetic. Adding one month to 31 January does not land on a non existent 31 February; PHP moves into early March, which may or may not be what a billing system wants. For monthly billing, many teams anchor to the first of the month or store an explicit billing day and clamp it to the last day of shorter months. Whatever rule you choose, write it down and test the January, February and December cases, because those are where date code earns its keep.
For storage, pass dates into queries as formatted Y-m-d or Y-m-d H:i:s strings, or bind the formatted value as a parameter. The safe binding pattern is shown in PHP PDO database queries, and it applies to date columns exactly as it does to names and emails: never build a query by joining raw user input into the string, dates included.
Conclusion
PHP date work becomes dependable once you standardise on a few habits: create dates with DateTime or DateTimeImmutable, parse known input with createFromFormat, format with the shared format characters, add time with DateInterval, compare objects directly, and store in UTC while displaying in the user’s timezone. With those patterns in place, due dates, event checks, countdowns and reports all follow from the same small set of examples.
Tagged: date datetime formatting php php snippets time



One thought on “PHP Date and Time: Format, Add Days and Compare Dates”