Calculating a date in the future or past

Calculating a date in the future or past

How to:

PHP makes date math simple with DateTime and DateInterval. Check this out:

// Today's date
$today = new DateTime();
echo $today->format('Y-m-d H:i:s') . "\n";

// Add 10 days
$today->add(new DateInterval('P10D'));
echo $today->format('Y-m-d H:i:s') . "\n";

// Subtract 2 months
$today->sub(new DateInterval('P2M'));
echo $today->format('Y-m-d H:i:s') . "\n";

Output might be:

2023-04-01 12:34:56
2023-04-11 12:34:56
2023-02-11 12:34:56

Deep Dive

Back in the day, PHP date calculations were more error-prone. strtotime, while still useful, can trip you up with edge cases. DateTime and DateInterval brought precision and object-oriented clarity.

Alternatives? Sure. Libraries like Carbon wrap PHP’s date functionality for more readability and features, but for many cases, PHP’s built-in classes will do just fine.

Under the hood, DateTime::add() and DateTime::sub() alter the object, so no need to reassign. They handle time units consistently, accounting for things like leap years and daylight saving time changes, which can be a real headache otherwise.

See Also