4

I want how to extract the exact number of nights. I tried to achieve this by two ways but doesn't work. It return 20 nights but in real, it is 21 nights (March have 31 days)

$startTimeStamp = strtotime("14-03-2017");                                   
$endTimeStamp = strtotime("04-04-2017");                                     

$timeDiff = abs($endTimeStamp - $startTimeStamp);                            

$numberDays = $timeDiff/86400;  // 86400 seconds in one day                  


$numberDays = intval($numberDays);                                           

echo $numberDays;                                                            

echo floor((strtotime('04-04-2017')-strtotime('14-03-2017'))/(60*60*24));    
NARTONIC
  • 452
  • 10
  • 22
  • I think you should +1 to whatever calculated days because output for any dates as per your requirement is not gonna give you output you want – Rahul Dec 16 '16 at 11:48
  • Possible duplicate of [Finding the number of days between two dates](http://stackoverflow.com/questions/2040560/finding-the-number-of-days-between-two-dates) – TIGER Dec 16 '16 at 11:56
  • 1
    Possible duplicate of [How to calculate the difference between two dates using PHP?](http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php) – toesslab Dec 16 '16 at 12:07

2 Answers2

9

Use the new DateTime extension, PHP 5.3+:

$date1 = new DateTime("2010-07-06");
$date2 = new DateTime("2010-07-09");

// this calculates the diff between two dates, which is the number of nights
$numberOfNights= $date2->diff($date1)->format("%a"); 
Octavian
  • 4,519
  • 8
  • 28
  • 39
-2

check this out for calculating nights

$start_ts = strtotime("2019-10-05"); 
$end_ts = strtotime("2019-10-06"); 
$diff = $end_ts - $start_ts; 
echo round($diff / 86400);//1 night

work like charm

Mohsen
  • 1,295
  • 1
  • 15
  • 45