0
0
PhpHow-ToBeginner · 3 min read

How to Add Days to Date in PHP: Simple Guide

In PHP, you can add days to a date using the DateTime class with its modify() method or by using the strtotime() function with a relative date string. Both methods let you easily increase a date by a specific number of days.
📐

Syntax

There are two common ways to add days to a date in PHP:

  • DateTime class: Create a DateTime object and use modify('+N days') where N is the number of days to add.
  • strtotime function: Use strtotime('+N days', $timestamp) to get a new timestamp, then format it back to a date string.
php
<?php
// Using DateTime class
$date = new DateTime('2024-06-01');
$date->modify('+5 days');
echo $date->format('Y-m-d');

// Using strtotime function
$originalDate = '2024-06-01';
$newDate = date('Y-m-d', strtotime('+5 days', strtotime($originalDate)));
echo "\n" . $newDate;
?>
Output
2024-06-06 2024-06-06
💻

Example

This example shows how to add 10 days to the current date using both DateTime and strtotime. It prints the new dates in Y-m-d format.

php
<?php
// Add 10 days using DateTime
$today = new DateTime();
$today->modify('+10 days');
echo "DateTime +10 days: " . $today->format('Y-m-d') . "\n";

// Add 10 days using strtotime
$now = date('Y-m-d');
$future = date('Y-m-d', strtotime('+10 days', strtotime($now)));
echo "strtotime +10 days: " . $future . "\n";
?>
Output
DateTime +10 days: 2024-06-16 strtotime +10 days: 2024-06-16
⚠️

Common Pitfalls

Common mistakes when adding days to dates in PHP include:

  • Not converting strings to timestamps before using strtotime.
  • Forgetting to format the DateTime object to a string before printing.
  • Using incorrect relative date strings like +5 day instead of +5 days.

Always check your date formats and conversions.

php
<?php
// Wrong: Using strtotime without converting original date
$originalDate = '2024-06-01';
// This will add days to current time, not original date
$wrongDate = date('Y-m-d', strtotime('+5 days'));
echo "Wrong: " . $wrongDate . "\n";

// Right: Convert original date to timestamp first
$correctDate = date('Y-m-d', strtotime('+5 days', strtotime($originalDate)));
echo "Right: " . $correctDate . "\n";
?>
Output
Wrong: 2024-06-06 Right: 2024-06-06
📊

Quick Reference

Here is a quick summary of how to add days to dates in PHP:

MethodUsageExample
DateTimemodify('+N days') $date = new DateTime('2024-06-01'); $date->modify('+5 days'); echo $date->format('Y-m-d');
strtotimestrtotime('+N days', strtotime($date)) $newDate = date('Y-m-d', strtotime('+5 days', strtotime('2024-06-01')));

Key Takeaways

Use the DateTime class with modify('+N days') for clear and flexible date manipulation.
strtotime('+N days', strtotime($date)) works well for quick timestamp calculations.
Always convert date strings to timestamps before adding days with strtotime.
Format DateTime objects to strings before outputting dates.
Check your relative date strings for correct syntax like '+5 days' not '+5 day'.