225 of 410 menu

The DateTime Class

The DateTime class is the main tool for working with dates and time in OOP style. It allows creating date/time objects, modifying them, and formatting output.

Current Moment in Time

Let's create a DateTime object with the current date and time:

<?php $date = new DateTime(); ?>

Specific Date

Let's create a DateTime object with a specified date:

<?php $date = new DateTime('2025-12-31'); ?>

Specific Date and Time

Let's create a DateTime object with a specified date and time:

<?php $date = new DateTime('2025-12-31 12:59:59'); ?>

Formatting Output

The created date can be output in a specified format using the format method. Let's do this for the current moment in time:

<?php $date = new DateTime(); echo $date->format('Y-m-d H:i:s'); ?>

Result (will change depending on the moment of execution):

'2025-11-15 14:25:00'

Formatting a Specified Date

Let's format a specified date:

<?php $date = new DateTime('2025-12-31'); echo $date->format('d.m.Y'); ?>

Code execution result:

'31.12.2025'

Adding an Interval

Adding an interval to a date is done through the add method:

<?php $date = new DateTime('2025-05-15'); $interval = new DateInterval('P10D'); // 10 days $date->add($interval); echo $date->format('Y-m-d'); ?>

Code execution result:

'2025-05-25'

Subtracting an Interval

Subtracting an interval from a date is done through the sub method:

<?php $date = new DateTime('2025-05-15'); $interval = new DateInterval('P1M2D'); // 1 month and 2 days $date->sub($interval); echo $date->format('Y-m-d'); ?>

Code execution result:

'2025-04-13'

Setting a New Date

You can set a new date for a DateTime object. This is done through the setDate method:

<?php $date = new DateTime(); $date->setDate(2025, 12, 31); echo $date->format('Y-m-d'); ?>

Code execution result:

'2025-12-31'

Setting Time

You can set a new time for a DateTime object. This is done through the setTime method:

<?php $date = new DateTime(); $date->setTime(15, 30, 0); echo $date->format('H:i:s'); ?>

Code execution result:

'15:30:00'

Comparing Dates

You can compare date objects:

<?php $date1 = new DateTime('2025-01-01'); $date2 = new DateTime('2025-02-01'); if ($date1 < $date2) { echo '+++'; } else { echo '---'; } ?>

Difference Between Dates

Using the diff method, you can calculate the difference between dates. The difference is returned as a DateInterval object:

<?php $date1 = new DateTime('2023-01-01'); $date2 = new DateTime('2023-02-15'); $interval = $date1->diff($date2); echo $interval->format('%m months %d days'); ?>

Code execution result:

'1 months 14 days'

Time Zone

When creating a DateTime object, you can specify the time zone:

<?php $timeZone = new DateTimeZone('Europe/Moscow'); $date = new DateTime('2025-12-31 23:59:59', $timeZone); echo $date->format('Y-m-d H:i:s e'); ?>

Code execution result:

'2025-12-31 23:59:59 Europe/Moscow'

See Also

byenru