Consider two dates '2011-01-01' and '2011-01-02'.I want to calculate the number of days between these two dates.The result what I want is 2 days(i.e including both start and end date).I used several date functions in php and mysql,but all returns 1 as the answer.

$date11 = '2011-01-01';
$date22 = '2011-01-02';
    $dt1 = new DateTime($date11);
$dt2 = new DateTime($date22);
$diff = $dt2->diff($dt1);
echo $diff->format("%a"); 

Any solution in php or mysql would be grateful.Thanks in advance.

有帮助吗?

解决方案

If you want to get 2 days for this interval you can just +1 to the result, because none of the combinations of functions will give 2 days.

$date11 = strtotime($date11);
$date22 = strtotime($date22);
$diff = $date22 - $date11;
$diff_in_days = floor($diff/(60*60*24)) + 1;

Example

其他提示

You can use DateTime and DateInterval and do you add 1 day?

DateTime DateInterval

<?php

    $d1 = new DateTime('2011-01-01');
    $d2 = new DateTime('2011-01-02');
    $d2->add(new DateInterval('24h'));

    $interval = $d2->diff($d1);

    $interval->format('%d Days');
    $interval->format('%h Hours');
?>

in mysql:

 select abs(datediff('2011-01-01','2011-01-02'))+1 as difference;
+------------+
| difference |
+------------+
|          2 |
+------------+
1 row in set (0.00 sec)

datediff() returns the number of days between the two dates, abs() makes sure we don't get negative values when switching first and second date and the final +1 because you wanted start and enddate to be included in the number.

Use DateDiff. The online docs have this answer as the first example:

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$datetime2->modify("+1 days");
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days'); // output

Another way to do this:

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
$diff = $interval->days + 1;
echo $diff . " days.";
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top