In this article, we will see how to subtract days from the given date object in PHP.
There are two methods to subtract the date from the given date, these are:
Using PHP date_sub() function
The date_sub() function is used to subtract some days, months, years, hours, minutes, and seconds from the given date. The function returns a DateTime object on success and returns FALSE on failure.
Syntax:
date_sub($object, $interval)Example: This examples uses date_sub() function to subtract days from date in PHP.
<?php
// Create a date object
$date = date_create('2023-10-25');
date_sub($date, date_interval_create_from_date_string('10 days'));
echo date_format($date, 'Y-m-d') . "\n";
// Create a date object (Current Date)
$date = date_create();
date_sub($date, date_interval_create_from_date_string('12 days'));
echo date_format($date, 'Y-m-d'). "\n";
?>
Output
2023-10-15 2023-10-18
Using subtraction and PHP strtotime() function
The strtotime() function is used to convert an English textual date-time description to a UNIX timestamp. The function returns the time in seconds since the Unix Epoch. It can return the English textual date-time in date format using the PHP date() function.
Syntax:
$newDate = date('Y-m-d', strtotime($date. ' - N days'))
Example: THis example uses subtraction and PHP strtotime() function to subtract days from date.
<?php
// Store the date into a variable
$date = '2023-10-25';
$newDate = date('Y-m-d', strtotime($date . ' - 10 days'));
echo $newDate . "\n";
// Create a date object (Current Date)
$newDate = date('Y-m-d', strtotime(' - 12 days'));
echo $newDate;
?>
Output
2023-10-15 2023-10-18