How to subtract some days in php?
The date_sub() is an inbuilt function in PHP which is used to subtract some days, months, years, hours, minutes, and seconds from given date. The function returns a DateTime object on success and returns FALSE on failure.
1. Code:
<?php function getDateSubWithFormat($dateStr, $day, $format = ''){ if(!isset($format) && $format == '' ){ $format = "Y-m-d H:i:s"; } if (is_null($dateStr) || trim($dateStr) == '' || "0000-00-00 00:00:00" == trim($dateStr)) { return null; } try { $d = date_create_from_format($format, $dateStr); if (false === $d) { throw new \Exception ("Invalid date"); } }catch (\Exception $e) { return $dateStr; } date_sub($d, date_interval_create_from_date_string("$day days")); $str = $d->format($format); return (false != $str) ? $str : null; } echo(getDateSubWithFormat("2022-06-27 01:12:22", 5, "Y-m-d H:i:s")); ?>
2. Example:
Input:
"2022-06-27 01:12:22", 5, "Y-m-d H:i:s"
Output:
2022-06-22 01:12:22