PHP: How to subtract days from a date

Updated: January 9, 2024 By: Guest Contributor Post a comment

Introduction

Dealing with dates and time is a common task in web development. PHP offers straightforward functions to manipulate dates, including subtracting days from a specific date. Whether you need to calculate past dates or simply modify dates for your application, this tutorial will guide you through various methods using PHP’s robust date-time functions.

Subtracting days using DateTime class

The DateTime class in PHP is an object-oriented way to handle dates and times. To subtract days from a date, follow these steps:

$date = new DateTime('2023-03-15');
$interval = new DateInterval('P10D');
$date->sub($interval);
echo $date->format('Y-m-d'); // Outputs: 2023-03-05

This code snippet creates a DateTime object for March 15, 2023, then subtracts a 10-day interval from it, resulting in March 5, 2023.

Using strtotime()

The strtotime() function is a versatile function to perform date arithmetic. Here’s how to use it:

$originalDate = '2023-03-15';
$alteredDate = strtotime('-10 days', strtotime($originalDate));
echo date('Y-m-d', $alteredDate); // Outputs: 2023-03-05

This utilizes strtotime to compute the time 10 days before the specified date.

Subtracting days using mktime()

The mktime() function can also be used to alter dates. This example shows subtracting days:

$originalDate = '2023-03-15';
list($year, $month, $day) = explode('-', $originalDate);
$alteredTimestamp = mktime(0, 0, 0, $month, $day - 10, $year);
echo date('Y-m-d', $alteredTimestamp); // Outputs: 2023-03-05

We break down the original date into its components, subtract the days, and use mktime to get the new timestamp, which we then format.

Advanced: Dealing with timezone and edge cases

When working with dates, timezone and edge cases (like leap years or month transitions) must be considered. The DateTime class can be set to the specific timezone and accounts for these cases automatically. Here’s an example:

$date = new DateTime('2023-03-15', new DateTimeZone('Europe/Paris'));
$interval = new DateInterval('P10D');
$date->sub($interval);
echo $date->format('Y-m-d T'); // Outputs: 2023-03-05 CET

If your requirements are more complex, involving such considerations, then the DateTime class should be your default choice because of its reliability and versatility.

Handling user input

When subtracting days from user-provided dates, ensure you validate and sanitize the data first to avoid any potential errors. Use the following filter to ensure the input is a valid date:

$userDate = '2023-03-15';
if ($userDate && strtotime($userDate)) {
    $date = new DateTime($userDate);
    $interval = new DateInterval('P10D');
    $date->sub($interval);
    echo $date->format('Y-m-d');
} else {
    echo 'Invalid date provided.';
}

This code ensures that the supplied date is valid before proceeding to subtract days.

Using a DatePeriod for a range

If you need to generate a series of dates by subtracting days in a range, consider using DatePeriod:

$begin = new DateTime('2023-03-30');
$end = (clone $begin)->sub(new DateInterval('P10D'));
$interval = new DateInterval('P1D');
$period = new DatePeriod($end, $interval, $begin);

foreach ($period as $date) {
    echo $date->format('Y-m-d') . "\n";
}

This scripts prints out all dates from 10 days prior to March 30, 2023, until March 30, inclusive, day by day.

Final Words

In this guide, we’ve explored several ways to subtract days from a date using PHP, ranging from basic to more advanced scenarios. Understanding how to manipulate dates and times is crucial for back-end development and allows for more dynamic, responsive applications. By mastering PHP’s date and time functions, you can now reliably calculate past or adjusted dates in your PHP applications.