减去日期并获得天数差异

时间:2013-12-04 05:08:16

标签: php html

首先,我要感谢您查看我的问题。所以我要做的就是减去2个日期并找出天数的差异。

我试过这样的事情

<!DOCTYPE html>
    <?php
        // initialize a session
        session_start();
    ?>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>

        <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">

            <input type="date" name="startdate" value="startdate"> 
            to <input type="date" name="enddate" value="enddate"> 
            <br/><br/>

            <input type="submit" name="Search" value="Search">

        </form>

        <?php 
            if(isset($_POST['Search'])) {
                $difInDays=$_POST['enddate']-$_POST['startdate'];
                //and $difInDays=$_POST['enddate']->diff($_POST['startdate']);
                echo $difInDays;
            }
        ?>

    </body>
</html>

任何建议都会很棒,非常感谢! :d

2 个答案:

答案 0 :(得分:1)

对于日期差异使用Diff php函数,如下所示:

   $date1 = new DateTime("2013-11-21 12:59:00");
    $date2 = new DateTime("2013-11-21 13:01:00");
    $interval = $date1->diff($date2); 

  echo "DIFF: ".$interval->format("%Y-%m-%d %H:%i:%s");

如果您在几天内感兴趣,只需获取d参数

答案 1 :(得分:1)

我一直主张将DateTimeDateInterval类用于此类事情。

$date1 = new DateTime($_POST['startdate']);
$date2 = new DateTime($_POST['enddate']);

/** @var DateInterval $diff */
$diff = date_diff($date1, $date2);

// You can look at the documentation for DateInterval,
//  but suffice it to say that its member variable "d" refers to the "day" part of the difference
echo $diff->d;

(这假设表格值以“Y-m-d”格式输入)