Finding the number of days between two dates

后端 未结 30 2457
心在旅途
心在旅途 2020-11-21 23:47

How to find number of days between two dates using PHP?

30条回答
  •  爱一瞬间的悲伤
    2020-11-22 00:19

    Well, the selected answer is not the most correct one because it will fail outside UTC. Depending on the timezone (list) there could be time adjustments creating days "without" 24 hours, and this will make the calculation (60*60*24) fail.

    Here it is an example of it:

    date_default_timezone_set('europe/lisbon');
    $time1 = strtotime('2016-03-27');
    $time2 = strtotime('2016-03-29');
    echo floor( ($time2-$time1) /(60*60*24));
     ^-- the output will be **1**
    

    So the correct solution will be using DateTime

    date_default_timezone_set('europe/lisbon');
    $date1 = new DateTime("2016-03-27");
    $date2 = new DateTime("2016-03-29");
    
    echo $date2->diff($date1)->format("%a");
     ^-- the output will be **2**
    

提交回复
热议问题