DateTime
PHP programs often use dates for blog posts, database entries and other website-related tasks. Fortunately the DateTime
class
is provided to make this easier.
With the DateTime
class
, and the immutable version (DateTimeImmutable
) we often need to specify intervals. This is done with DateInterval
.
This example program uses DateTime
, DateTimeImmutable
, and DateInterval
. It first creates dates based on the current date in the system environment.
DateTime
based on the current time and date. We then add 1 day to it with a DateInterval
.DateTimeImmutable
, which is never changed—we must assign to the result of methods like add()
.DateTime
(or DateTimeImmutable
) from a format string
, which lets us specify a specific date.// Part 1: get current datetime, and add 1 day to it, and display it. $now = new DateTime(); $now->add(new DateInterval("P1D")); print_r($now); // Part 2: add 1 year to current datetime immutable. $now = new DateTimeImmutable(); $changed = $now->add(new DateInterval("P1Y")); print_r($changed); // Part 3: create a specific date, and then subtract 1 month from it. $test = new DateTimeImmutable("2023-3-10"); $changed = $test->sub(new DateInterval("P1M")); print_r($changed);DateTime Object ( [date] => 2023-06-08 15:33:18.213625 [timezone_type] => 3 [timezone] => UTC ) DateTimeImmutable Object ( [date] => 2024-06-07 15:33:18.213644 [timezone_type] => 3 [timezone] => UTC ) DateTimeImmutable Object ( [date] => 2023-02-10 00:00:00.000000 [timezone_type] => 3 [timezone] => UTC )
For standard behavior, it is probably better to use DateTimeImmutable
. With the immutable class
, we must copy the results of each call to add()
and sub()
.
DateTimeImmutable
class
has functionality that is more similar to other popular languages, which is a clear advantage.Representing dates and times is always complex. In PHP we must use format strings for DateTimes
, and also format strings for DateIntervals
(which are like time spans).