Search code examples
phpsymfony-3.4orocrm

how to find number of days in PHP when from date and to date is same


i am trying to calculate between two dates using \DateTime::createFromFormat .

but i am not able to find the difference between two same dates . like for one day it should show one days. below is my code.

    $fromDate = \DateTime::createFromFormat('M j, Y', $request->get('fromDateVal')); 
    $toDate = \DateTime::createFromFormat('M j, Y', $request->get('toDateVal')); 
    $diffdays = $toDate->diff($fromDate) ;

any help will be helpful.

i am getting this

    DateInterval {#7658
  interval: 0s
  +"y": 0
  +"m": 0
  +"d": 0
  +"h": 0
  +"i": 0
  +"s": 0
  +"f": 0.0
  +"weekday": 0
  +"weekday_behavior": 0
  +"first_last_day_of": 0
  +"invert": 0
  +"days": 0
  +"special_type": 0
  +"special_amount": 0
  +"have_weekday_relative": 0
  +"have_special_relative": 0
}


Solution

  • Use DateTime::diff() function

    The DateTime::diff() function is an inbuilt function in PHP which is used to return the difference between two given DateTime objects.

    <?php
    
    // Initialising the two datetime objects 
    
    $datetime1 = new DateTime('2019-9-10'); 
    $datetime2 = new DateTime('2019-9-15'); 
    
    // Calling the diff() function on above 
    $difference = $datetime1->diff($datetime2); 
    
    // Getting the difference between two 
    echo $difference->format('%R%a days'); 
    
    ?>