Skip to content
PHP Logo

How can DateTime objects be used effectively in PHP for date calculations?

When working with date calculations in PHP, using DateTime objects can provide a more flexible and reliable way to manipulate dates and times. DateTime objects offer a wide range of methods for adding or subtracting time intervals, comparing dates, formatting dates, and more. By utilizing DateTime objects, you can perform complex date calculations with ease and accuracy.

php
// Create a DateTime object for the current date
$currentDate = new DateTime();

// Add 1 day to the current date
$currentDate->modify('+1 day');

// Format the date in a specific format
$formattedDate = $currentDate->format('Y-m-d');

echo $formattedDate;