skip to Main Content

How can I obtain a date in PHP that is both three months and three days ahead of the current system date?

    $originalDate = date('m-d-Y'); // The original date
    $monthsToSubtract = 3;

    $newDate = date('m-d-Y', strtotime(-$monthsToSubtract, strtotime($originalDate)));


    return $newDate;

The code provided is giving me an unexpected or unusual result.
Output =>> 01-01-1970

2

Answers


  1. You can do it through DateTime PHP class, for reference you can visit the link https://www.php.net/manual/en/class.datetime.php

    $currentDate = new DateTime('2023-07-30'); // Get the current date and time
    
    $currentDate->modify('-3 months'); // Subtract 3 months
    
    $newDate = $currentDate->format('Y-m-d');
    
    return $newDate;
    
    
    Login or Signup to reply.
  2. I would use the DateTime class as suggested by Kamran Allana. But I modified it to reflect more to the question.

        <?php
        $myDate = new DateTime();
        $myDate->modify('-3 day');
        $myDate->modify('-3 month');
    
       // and now you could either continue with this object $myDate
       // or convert it to a string:
    
        $newDate = $myDate('m-d-Y');
        ?>
    

    Notice the string $newDate cannot be used to do calculations

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search