Real‑world examples of practical PHP date and time functions examples
Quick, real examples of practical PHP date and time functions examples
Let’s start with concrete code. These examples of practical PHP date and time functions examples mirror what you actually do in apps: show dates to humans, store dates for machines, and avoid time‑zone disasters.
Formatting a human‑friendly date for users
You rarely show raw timestamps to users. You show something like “March 10, 2025, 2:45 PM”. Here’s a straightforward example of using DateTime and date() to format a date for display:
// Current time in server default timezone
$now = new DateTime();
echo $now->format('F j, Y, g:i A');
// Example output: March 10, 2025, 2:45 PM
// Same idea using date() with a Unix timestamp
$timestamp = time();
echo date('Y-m-d H:i:s', $timestamp);
// Example output: 2025-03-10 14:45:00
This is one of the best examples of where PHP’s date and time functions shine: simple formatting that works consistently across PHP 7 and 8.
Storing timestamps safely in the database (UTC best practice)
Real‑world apps usually store all timestamps in UTC, then convert to a user’s timezone on output. This avoids a lot of pain with daylight saving time and moving servers.
// Always create and store in UTC
$utc = new DateTimeZone('UTC');
\(createdAt = new DateTime('now', \)utc);
// Store this string in a DATETIME or TIMESTAMP column (preferably as UTC)
\(dbValue = \)createdAt->format('Y-m-d H:i:s');
// Later, when reading from DB and showing to a user in New York
$userTz = new DateTimeZone('America/New_York');
\(fromDb = DateTime::createFromFormat('Y-m-d H:i:s', \)dbValue, $utc);
\(fromDb->setTimezone(\)userTz);
echo $fromDb->format('M j, Y g:i A T');
// Example: Mar 10, 2025 10:45 AM EDT
If you’re building anything multi‑region, this pattern belongs in your list of examples of practical PHP date and time functions examples.
Time zone aware examples of practical PHP date and time functions examples
Time zones are where things go wrong in production. PHP’s DateTimeZone and IntlDateFormatter are your friends here.
Converting between time zones for international users
Say you run a SaaS product with users in London and Los Angeles. You store UTC in the database, but you want each user to see their local time.
$utc = new DateTimeZone('UTC');
\(eventTimeUtc = new DateTime('2025-08-15 18:00:00', \)utc);
$london = new DateTimeZone('Europe/London');
$la = new DateTimeZone('America/Los_Angeles');
\(londonTime = clone \)eventTimeUtc;
\(londonTime->setTimezone(\)london);
\(laTime = clone \)eventTimeUtc;
\(laTime->setTimezone(\)la);
echo 'London: ' . $londonTime->format('Y-m-d H:i T') . PHP_EOL;
echo 'Los Angeles: ' . $laTime->format('Y-m-d H:i T') . PHP_EOL;
This example of timezone conversion is exactly what you need for calendars, meeting schedulers, and booking systems.
Handling daylight saving time safely
Daylight saving time (DST) is where naive code breaks. Adding 3600 * 24 seconds to “yesterday” can land you in the wrong local time on DST transitions. Use DateInterval with DateTime instead:
$tz = new DateTimeZone('America/New_York');
// Date near DST change
\(start = new DateTime('2025-03-09 01:30:00', \)tz); // Before US spring DST shift
\(nextDay = clone \)start;
$nextDay->add(new DateInterval('P1D'));
echo 'Start: ' . $start->format('Y-m-d H:i:s T') . PHP_EOL;
echo 'Next day: ' . $nextDay->format('Y-m-d H:i:s T') . PHP_EOL;
This is one of the most practical PHP date and time functions examples you can learn: never do manual second arithmetic when a DateInterval can do it for you.
For more background on time zone data and DST rules, the IANA time zone database, used by PHP internally, is documented at https://www.iana.org/time-zones.
Date calculations: intervals, periods, and recurring events
Modern apps love recurring events: subscriptions, weekly standups, monthly invoices. These are classic examples of practical PHP date and time functions examples that go beyond simple formatting.
Adding and subtracting intervals
Use DateInterval for human‑friendly operations like “add 1 month” or “subtract 30 minutes.”
$now = new DateTime('now', new DateTimeZone('UTC'));
// Subscription: trial ends in 14 days
\(trialEnd = clone \)now;
$trialEnd->add(new DateInterval('P14D'));
// Reminder: send 30 minutes before trial ends
\(reminder = clone \)trialEnd;
$reminder->sub(new DateInterval('PT30M'));
echo 'Now: ' . $now->format('Y-m-d H:i:s') . PHP_EOL;
echo 'Trial end: ' . $trialEnd->format('Y-m-d H:i:s') . PHP_EOL;
echo 'Reminder: ' . $reminder->format('Y-m-d H:i:s') . PHP_EOL;
Note how the interval spec works:
P14Dmeans 14 daysPT30Mmeans 30 minutes
These readable strings are one of the best examples of how PHP makes date intervals manageable.
Generating recurring dates (weekly or monthly)
If you need a schedule — say, every Monday for 8 weeks — DatePeriod is your tool.
$start = new DateTime('2025-01-06', new DateTimeZone('UTC')); // A Monday
$interval = new DateInterval('P1W'); // 1 week
$occurrences = 8;
\(period = new DatePeriod(\)start, \(interval, \)occurrences);
foreach (\(period as \)occurrence) {
echo $occurrence->format('Y-m-d') . PHP_EOL;
}
This example of DatePeriod is perfect for generating class schedules, recurring meetings, or subscription billing dates.
Parsing user input and validating dates
Users will type dates in every format under the sun. Your job is to normalize that into a DateTime object or reject it politely.
Parsing different input formats safely
Here is one of the more realistic examples of practical PHP date and time functions examples: handling messy input.
$inputs = [
'2025-12-31',
'12/31/2025',
'31-12-2025', // European style
];
$formats = [
'Y-m-d',
'm/d/Y',
'd-m-Y',
];
foreach (\(inputs as \)input) {
$date = null;
foreach (\(formats as \)format) {
\(date = DateTime::createFromFormat(\)format, $input, new DateTimeZone('UTC'));
$errors = DateTime::getLastErrors();
if (\(date !== false && \)errors['warning_count'] === 0 && $errors['error_count'] === 0) {
echo "Input: \(input => " . \)date->format('Y-m-d') . PHP_EOL;
break;
}
}
if (!$date) {
echo "Input: $input => invalid date" . PHP_EOL;
}
}
This pattern — try a few formats, validate, then normalize — is one of the best examples to keep in your toolkit.
Validating dates before saving
Sometimes you just want to know whether a date is valid. PHP’s checkdate() is made for that:
$month = 2;
$day = 29;
$year = 2025;
if (checkdate(\(month, \)day, $year)) {
echo 'Valid date';
} else {
echo 'Invalid date'; // 2025 is not a leap year
}
This small example of validation is perfect for quick checks before hitting the database.
Working with Unix timestamps and performance
Timestamps are still useful: they’re compact, fast to compare, and easy to store as integers.
Converting between DateTime and timestamps
You often move between DateTime objects and Unix timestamps for performance or compatibility with other systems.
// DateTime to timestamp
$dt = new DateTime('2025-05-01 12:00:00', new DateTimeZone('UTC'));
\(timestamp = \)dt->getTimestamp();
// Timestamp to DateTime
\(fromTs = (new DateTime('@' . \)timestamp))->setTimezone(new DateTimeZone('UTC'));
echo 'Timestamp: ' . $timestamp . PHP_EOL;
echo 'From TS: ' . $fromTs->format('Y-m-d H:i:s') . PHP_EOL;
This is one of those quiet examples of practical PHP date and time functions examples you’ll reuse constantly when integrating with APIs that speak only in Unix time.
Measuring execution time for debugging
When you need to profile a slow function, timestamps give you a quick, dirty answer.
$start = microtime(true);
// Some heavy operation
usleep(250000); // 0.25 seconds
$end = microtime(true);
\(durationMs = (\)end - $start) * 1000;
echo 'Duration: ' . number_format($durationMs, 2) . ' ms';
Not fancy, but very practical when you’re trying to see if a new query or API call is misbehaving.
Localization and international formatting
If you have international users, IntlDateFormatter lets you format dates in a way that feels natural to them.
Localized formatting with IntlDateFormatter
$tz = new DateTimeZone('Europe/Berlin');
\(dt = new DateTime('2025-11-05 18:30:00', \)tz);
$formatter = new IntlDateFormatter(
'de_DE',
IntlDateFormatter::LONG,
IntlDateFormatter::SHORT,
$tz->getName(),
IntlDateFormatter::GREGORIAN
);
echo \(formatter->format(\)dt);
// Example output: 5. November 2025, 18:30
If you want to build something that respects user locale and language, this is one of the best examples you can adapt. For general guidance on internationalization concepts (not PHP‑specific, but still useful), the W3C has solid documentation at https://www.w3.org/International/.
Modern PHP tips: immutability and type safety
PHP 8 encourages you to write safer, more predictable date code. Two patterns stand out in real examples of practical PHP date and time functions examples today.
Using DateTimeImmutable to avoid surprises
DateTime is mutable; changing it in one place can unexpectedly affect other references. DateTimeImmutable avoids that.
$start = new DateTimeImmutable('2025-01-01 00:00:00', new DateTimeZone('UTC'));
// add() returns a NEW object instead of modifying the original
\(nextWeek = \)start->add(new DateInterval('P1W'));
// $start is still 2025-01-01
// $nextWeek is 2025-01-08
In 2024–2025 codebases, using DateTimeImmutable in domain logic is becoming a common pattern, especially in frameworks and libraries that care about predictability.
Leveraging type hints and strict types
Combine date classes with strict typing for cleaner APIs:
declare(strict_types=1);
function formatInvoiceDate(DateTimeInterface \(date, string \)timezone): string
{
\(tz = new DateTimeZone(\)timezone);
\(local = (new DateTimeImmutable(\)date->format('c')))->setTimezone($tz);
return $local->format('Y-m-d');
}
$invoiceDateUtc = new DateTimeImmutable('2025-02-10 15:00:00', new DateTimeZone('UTC'));
echo formatInvoiceDate($invoiceDateUtc, 'America/Chicago');
This example of a typed helper function is exactly the sort of pattern you see in modern Laravel or Symfony projects.
Frequently asked questions about PHP date and time examples
What are some real examples of practical PHP date and time functions examples in production apps?
Common real examples include formatting order timestamps on receipts, calculating subscription renewal dates, logging user activity in UTC, scheduling reminder emails a few hours before an event, and converting event times for users in different time zones. All of those rely on DateTime, DateInterval, and DateTimeZone working together.
Can you give an example of handling user time zones correctly?
A reliable example of good practice is: store everything in UTC using DateTime('now', new DateTimeZone('UTC')), save that to your database, then on output create a DateTime from the stored value and call setTimezone() with the user’s IANA time zone, such as America/New_York. Format that result for display. Never store mixed time zones in the same column.
Should I use timestamps or DATETIME strings in my database?
Both work. Many teams store UTC as DATETIME or TIMESTAMP because it is easier to debug by eye (2025-03-10 14:45:00 is readable). Timestamps are compact and fast for comparisons, but you lose that readability. The more important rule is consistency: pick one format, keep it in UTC, and convert at the application edge.
How do I avoid daylight saving time bugs in PHP?
Use named time zones like America/Los_Angeles, avoid adding raw seconds for date math, and prefer DateInterval with add() and sub(). When in doubt, test your code around known DST transition dates. The IANA database and official time zone references, such as the NIST time services at https://www.nist.gov/pml/time-and-frequency-division, are good sources for understanding when those changes occur.
Is it okay to use the plain date() function in new PHP code?
date() is still fine for quick formatting when you already have a timestamp, but for anything that touches time zones or business rules, prefer DateTime or DateTimeImmutable. Those classes compose better, are easier to test, and match how modern frameworks expect you to work.
If you keep these examples of practical PHP date and time functions examples close at hand, you’ll spend less time chasing timezone bugs and more time shipping features that users actually notice.
Related Topics
Real‑world examples of using Composer for PHP dependency management
Real-world examples of hosting open source SaaS with PHP
The best examples of simple PHP function examples for beginners
The best examples of creating a PHP session: 3 practical examples for real projects
The best examples of learn PHP arrays and loops with practical examples
Real‑world examples of practical PHP date and time functions examples
Explore More PHP Code Snippets
Discover more examples and insights in this category.
View All PHP Code Snippets