简体   繁体   中英

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
}

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'); 

?>

Just do

if($fromDate == $toDate){
    $diffdays = 0;
}

I don't know if this is what you want. But basically add a condition to see if they are the same, and add the value you want. I added 0 since I think that's what the difference should be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM