Summary: in this tutorial, you’ll learn how to work with the date and time in an object-oriented way.
Introduction to the PHP DateTime class #
PHP provides a set of date and time classes that allow you to work with the date and time in an object-oriented way.
To create a new date and time object, you use the DateTime
class. For example:
<?php
$datetime = new DateTime();
var_dump($datetime);
Code language: PHP (php)
Output:
object(DateTime)#1 (3) {
["date"]=> string(26) "2021-07-15 06:30:40.294788"
["timezone_type"]=> int(3)
["timezone"]=> string(13) "Europe/Berlin"
}
Code language: PHP (php)
The DateTime
object represents the current date and time in the timezone specified in the PHP configuration file (php.ini
)
To set a new timezone, you create a new DateTimeZone
object and pass it to the setTimezone()
method of the DateTime
object:
<?php
$datetime = new DateTime();
$timezone = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($timezone);
var_dump($datetime);
Code language: PHP (php)
Output:
object(DateTime)#1 (3) {
["date"]=> string(26) "2021-07-14 21:33:27.986925"
["timezone_type"]=> int(3)
["timezone"]=> string(19) "America/Los_Angeles"
}
Code language: PHP (php)
In this example, we create a new DateTimeZone
object and set it to "America/Los_Angeles"
. To get valid timezones supported by PHP, check out the timezone list.
To format a DateTime
object, you use the format()
method. The format string parameters are the same as those you use for the date()
function. For example:
<?php
$datetime = new DateTime();
echo $datetime->format('m/d/Y g:i A');
Code language: PHP (php)
Output:
07/15/2021 6:38 AM
Code language: PHP (php)
To set a specific date and time, you can pass a date & time string to the DateTime()
constructor like this:
<?php
$datetime = new DateTime('12/31/2019 12:00 PM');
echo $datetime->format('m/d/Y g:i A');
Code language: PHP (php)
Or you can use the setDate()
function to set a date:
<?php
$datetime = new DateTime();
$datetime->setDate(2020, 5, 1);
echo $datetime->format('m/d/Y g:i A');
Code language: PHP (php)
Output:
05/01/2020 6:42 AM
Code language: PHP (php)
The time is derived from the current time. To set the time, you use the setTime()
function:
<?php
$datetime = new DateTime();
$datetime->setDate(2020, 5, 1);
$datetime->setTime(5, 30, 0);
echo $datetime->format('m/d/Y g:i A');
Code language: PHP (php)
Output:
05/01/2020 5:30 AM
Code language: PHP (php)
Since the setDate()
, setTime()
, and setTimeZone()
method returns the DateTime
object, you can chain them like this which is quite convenient.
<?php
$datetime = new DateTime();
echo $datetime->setDate(2020, 5, 1)
->setTime(5, 30)
->setTimezone(new DateTimeZone('America/New_York'))
->format('m/d/Y g:i A');
Code language: PHP (php)
Output:
04/30/2020 11:30 PM
Code language: PHP (php)
Creating a DateTime object from a string #
When you pass the date string ’06/08/2021′ to the DateTime()
constructor or setDate()
function, PHP interprets it as m/d/Y
. For example:
<?php
$datetime = new DateTime('06/08/2021');
echo $datetime->format('F jS, Y');
Code language: PHP (php)
Output:
June 8th, 2021
Code language: PHP (php)
If you want to pass it as August 6th, 2021, you need to use the – or . instead of /. For example:
<?php
$datetime = new DateTime('06-08-2021');
echo $datetime->format('F jS, Y');
Code language: PHP (php)
Output:
August 6th, 2021
Code language: PHP (php)
However, if you want to parse the date string ’06/08/2021′ as d/m/Y, you need to replace the / with – or . manually:
<?php
$ds = '06/08/2021';
$datetime = new DateTime(str_replace('/', '-', $ds));
echo $datetime->format('F jS, Y');
Code language: PHP (php)
Output:
August 6th, 2021
Code language: PHP (php)
A better way to do it is to use the createFromFormat()
static method of the DateTime
object:
<?php
$ds = '06/08/2021';
$datetime = DateTime::createFromFormat('d/m/Y', $ds);
echo $datetime->format('F jS, Y');
Code language: PHP (php)
In this example, we pass the date format as the first argument and the date string as the second argument.
Note that when you pass a date string without the time, the DateTime()
constructor uses midnight time. However, the createFromFormat()
method uses the current time.
Comparing two DateTime objects #
PHP allows you to compare two DateTime objects using the comparison operators including >, >=, <, <=, ==, <=>. For example:
<?php
$datetime1 = new DateTime('01/01/2021 10:00 AM');
$datetime2 = new DateTime('01/01/2021 09:00 AM');
var_dump($datetime1 < $datetime2); // false
var_dump($datetime1 > $datetime2); // true
var_dump($datetime1 == $datetime2); // false
var_dump($datetime1 <=> $datetime2); // 1
Code language: PHP (php)
Calculating the differences between two DateTime objects #
The diff()
method of the DateTime()
object returns the difference between two DateTime()
objects as a DateInterval
object. For example:
<?php
$dob = new DateTime('01/01/1990');
$to_date = new DateTime('07/15/2021');
$age = $to_date->diff($dob);
var_dump($age);
Code language: PHP (php)
Output:
object(DateInterval)#3 (16) {
["y"]=> int(31)
["m"]=> int(6)
["d"]=> int(14)
["h"]=> int(0)
["i"]=> int(0)
["s"]=> int(0)
["f"]=> float(0)
["weekday"]=> int(0)
["weekday_behavior"]=> int(0)
["first_last_day_of"]=> int(0)
["invert"]=> int(1)
["days"]=> int(11518)
["special_type"]=> int(0)
["special_amount"]=> int(0)
["have_weekday_relative"]=> int(0)
["have_special_relative"]=> int(0)
}
Code language: PHP (php)
The DateInterval
represents the differences between two dates in the year, month, day, hour, etc. To format the difference, you use the DateInterval
‘s format. For example:
<?php
$dob = new DateTime('01/01/1990');
$to_date = new DateTime('07/15/2021');
echo $to_date->diff($dob)->format('%Y years, %m months, %d days');
Code language: PHP (php)
Output:
31 years, 6 months, 14 days
Code language: PHP (php)
Check out all the DateInterval format parameters.
Adding an interval to a DateTime object #
To add an interval to date, you create a new DateInterval
object and pass it to the add()
method. The following example adds 1 year 2 months to the date 01/01/2021
:
<?php
$datetime = new DateTime('01/01/2021');
$datetime->add(new DateInterval('P1Y2M'));
echo $datetime->format('m/d/Y');
Code language: PHP (php)
Output:
03/01/2022
Code language: PHP (php)
To format a date interval, you use the date interval format strings.
To subtract an interval from a DateTime
object, you create a negative interval and use the add()
method.
Summary #
- Use the
DateTime
class to work with the date and time. - Use the
DateTimeZone
class to work with time zones. - Use the comparison operators to compare two
DateTime
objects. - Use the
diff()
method to calculate the difference between toDateTime
objects. - Use the
DateInterval
class to represent a date and time interval. - Use the
add()
method to add an interval to or subtract an interval from aDateTime
object.