The DateTime class
Learn object-oriented date operations with the DateTime class.
Introducing the DateTime class
PHP also offers an object-oriented way to work with dates: the DateTime class. It represents a date as an object and uses methods for formatting and calculations.
For example, $date = new DateTime('2024-06-15'); creates an object for a specific date. Calling new DateTime() with no argument gives the current time.
DateTime is more flexible than the date() function; it reduces errors in date math.
DateTime construction and format()
You format a DateTime object with the ->format() method. The method accepts the same format characters as the date() function.
For example, after $date = new DateTime('2024-08-20');, the call echo $date->format('d.m.Y'); prints 20.08.2024. format('H:i:s') gives the time, format('Y-m-d') the date.
Because the format characters match date(), switching between the two is easy.
Exercise Format a DateTime object
Create an object with new DateTime('2024-08-20') and assign it to $date. Then print it with echo $date->format('d.m.Y');.
Show example solution
Create with $date = new DateTime('2024-08-20'); then add echo $date->format('d.m.Y');
Example solution:
<?php
date_default_timezone_set('UTC');
$date = new DateTime('2024-08-20');
echo $date->format('d.m.Y');
Test yourself
-
What does the DateTime class's format() method return?
- A timestamp (integer)
- A new DateTime object
- A formatted date string
- A boolean
Show answer
A formatted date string — Correct. format() returns a formatted date string.
-
Create a DateTime for a specific date
$date = new DateTime('____');Show answer
$date = new DateTime('2024-06-15'); -
Match DateTime usages
- new DateTime()
- Current time
- new DateTime('2024-01-15')
- A specific date
- ->format('Y')
- Year string
- ->format('H:i:s')
- Time string