Time in PHP

Our first program will demonstrate how to work with time and durations in PHP. Here’s the full source code with explanations:

<?php

// We'll start by getting the current time.
$now = new DateTime();
echo $now->format('Y-m-d H:i:s.u P T') . "\n";

// You can create a DateTime object by providing the 
// year, month, day, etc. Times are always associated
// with a timezone.
$then = new DateTime('2009-11-17 20:34:58.651387', new DateTimeZone('UTC'));
echo $then->format('Y-m-d H:i:s.u P T') . "\n";

// You can extract the various components of the time
// value as expected.
echo $then->format('Y') . "\n";
echo $then->format('F') . "\n";
echo $then->format('d') . "\n";
echo $then->format('H') . "\n";
echo $then->format('i') . "\n";
echo $then->format('s') . "\n";
echo $then->format('u') . "\n";
echo $then->getTimezone()->getName() . "\n";

// The day of the week is also available.
echo $then->format('l') . "\n";

// These methods compare two times, testing if the
// first occurs before, after, or at the same time
// as the second, respectively.
echo ($then < $now ? 'true' : 'false') . "\n";
echo ($then > $now ? 'true' : 'false') . "\n";
echo ($then == $now ? 'true' : 'false') . "\n";

// The diff method returns a DateInterval object representing
// the interval between two times.
$diff = $now->diff($then);
echo $diff->format('%R%y years, %m months, %d days, %H hours, %i minutes, %s seconds') . "\n";

// We can compute the length of the duration in
// various units.
echo $diff->days * 24 + $diff->h . "\n";
echo $diff->days * 24 * 60 + $diff->h * 60 + $diff->i . "\n";
echo $diff->days * 24 * 60 * 60 + $diff->h * 60 * 60 + $diff->i * 60 + $diff->s . "\n";

// You can use add and sub to advance a time by a given
// interval, or move backwards by an interval.
$interval = new DateInterval('P10Y10M10DT10H10M10S');
echo $then->add($interval)->format('Y-m-d H:i:s.u P T') . "\n";
echo $then->sub($interval)->format('Y-m-d H:i:s.u P T') . "\n";

?>

To run the program, save it as time_example.php and use php:

$ php time_example.php
2023-06-09 12:34:56.789012 +02:00 CEST
2009-11-17 20:34:58.651387 +00:00 UTC
2009
November
17
20
34
58
651387
UTC
Tuesday
true
false
false
+13 years, 6 months, 23 days, 16 hours, 0 minutes, 58 seconds
118296
7097760
425865658
2020-10-27 06:45:08.651387 +00:00 UTC
2009-11-17 20:34:58.651387 +00:00 UTC

This example demonstrates how to work with dates, times, and durations in PHP using the DateTime, DateTimeZone, and DateInterval classes. These classes provide powerful functionality for handling time-related operations in PHP applications.

Next, we’ll look at the related idea of time relative to the Unix epoch.