The DateTime Class

DateTime is an object-oriented way to work with dates and time.

Syntax$date = new DateTime("2026-07-04"); $date->format("Y-m-d");

The DateTime class offers an object-oriented approach to dates. You can create one, format it, and calculate differences between dates.

Use format() to output it and diff() to compare two dates, which returns a DateInterval.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Calculate the number of days remaining on a subscription by diffing two DateTime objects.
  • Create a DateTime from a stored UTC timestamp and convert it to the user's local timezone for display.
  • Use DateInterval to add a fixed trial period to a signup date when creating subscription records.

More examples

Creating and formatting DateTime

DateTime wraps a timestamp in an object; format() uses the same characters as the procedural date() function.

Example · php
<?php
$dt = new DateTime();
echo $dt->format('Y-m-d H:i:s');

$birthday = new DateTime('1990-06-15');
echo $birthday->format('l, d F Y'); // Sunday, 15 June 1990

Calculating date differences

diff() returns a DateInterval object whose ->days property gives the total number of days between two dates.

Example · php
<?php
$signup  = new DateTime('2026-01-01');
$today   = new DateTime('today');
$diff    = $today->diff($signup);

echo "{$diff->days} days since signup";

Timezone conversion

setTimezone() shifts a DateTime to a different timezone; cloning preserves the original for comparison.

Example · php
<?php
$utc   = new DateTime('2026-07-16 12:00:00', new DateTimeZone('UTC'));
$tokyo = clone $utc;
$tokyo->setTimezone(new DateTimeZone('Asia/Tokyo'));

echo $utc->format('H:i T');   // 12:00 UTC
echo $tokyo->format('H:i T'); // 21:00 JST

Discussion

  • Be the first to comment on this lesson.