How to Subtract Days from Date in PHP?
Last Updated :
20 Nov, 2023
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:
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
<?php
$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" ;
$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
<?php
$date = '2023-10-25' ;
$newDate = date ( 'Y-m-d' , strtotime ( $date . ' - 10 days' ));
echo $newDate . "\n" ;
$newDate = date ( 'Y-m-d' , strtotime ( ' - 12 days' ));
echo $newDate ;
?>
|
Output
2023-10-15
2023-10-18
Share your thoughts in the comments
Please Login to comment...