DateTime, DateInterval Examples
This page was last reviewed on 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 7, 2023 (new).
© 2007-2024 Sam Allen.