phpdatestrtotime

define a sting as a date and add days


I have a string that represent a date (ex. 01/10/2022 d/m/Y) and I want to add 90 days to this date, the problem I think I have is that php dont know how do add the 90 days to this date because is a string. I tried different solution posted by others but without a good result.

One example that I tried is:

$nextduedate = "01/10/2022";
$myDateTime = DateTime::createFromFormat('d/m/Y', $nextduedate);
$myDateTime = $myDateTime->format('d/m/Y');
$number_of_days = 90;
$str =' + '. $number_of_days. ' days';
$myDateTime = date('d/m/Y', strtotime($myDateTime. $str));
echo $myDateTime;

adn the result is 10/04/2022 istead of 01/01/2023

I know im missing something but I dont know what.


Solution

  • If you use Date Object, this script can help you. You have to use "modify" function

    <?
    $startEntry = "01/10/2022";
    $nbDays     = 90;
    
    
    $stringDiff = "+".$nbDays." days";
    
    $startDate  = DateTime::createFromFormat('d/m/Y', $startEntry);
    $endDate    = $startDate->modify($stringDiff);
    
    echo $endDate->format('d/m/Y');
    ?>