Home
PHP
DateTime, DateInterval Examples
Updated Jun 7, 2023
Dot Net Perls
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.
Part 1 We create a DateTime based on the current time and date. We then add 1 day to it with a DateInterval.
Part 2 Here we use a DateTimeImmutable, which is never changed—we must assign to the result of methods like add().
Part 3 It is possible to create a 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().
Info The 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).
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 7, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen