This site uses tracking technologies. You may opt in or opt out of the use of these technologies.

Back to PHP

PHP Date and Time: Date and time handling with DateTime class

The DateTime class in PHP is a powerful and flexible way to handle date and time operations.

The DateTime class in PHP is a powerful and flexible way to handle date and time operations. It provides a variety of methods for creating, formatting, modifying, and comparing dates and times. Here’s an overview of how to use the DateTime class effectively.

1. Creating a DateTime Object

You can create a new DateTime object for the current date and time or specify a date and time.

// Current date and time
$currentDateTime = new DateTime();
// Specified date and time
$specifiedDate = new DateTime('2023-01-01 12:00:00');

You can also create a DateTime object from a timestamp:

// DateTime from timestamp
$timestamp = 1672531199;
$dateFromTimestamp = (new DateTime())->setTimestamp($timestamp);

2. Formatting Dates

The format() method allows you to format a DateTime object into a string.

echo $currentDateTime->format('Y-m-d H:i:s'); // e.g., 2024-11-03 14:35:23

Some common format characters include:

  • Y – Full numeric year (e.g., 2024)

  • m – Numeric month (01 to 12)

  • d – Day of the month (01 to 31)

  • H – Hour (00 to 23)

  • i – Minutes (00 to 59)

  • s – Seconds (00 to 59)

3. Modifying Dates

You can modify a date using methods like modify() or add(). The modify() method takes a string relative to the current date.

// Add one day
$currentDateTime->modify('+1 day');
// Subtract two hours
$currentDateTime->modify('-2 hours');

The add() and sub() methods allow you to add or subtract a DateInterval.

$interval = new DateInterval('P1D'); // 1 day
$currentDateTime->add($interval);
$interval = new DateInterval('PT2H'); // 2 hours
$currentDateTime->sub($interval);