当日期通过post变量传递到另一个页面并回显php中的差异时,如何获得日期差异

I tried with the below code to find the difference between two dates which is passed through post variable and print, but failed.

$fromdate=$_POST['from_date']; $todate=$_POST['to_date']; $date1 = new DateTime($fromdate); //inclusive $date2 = new DateTime($todate); //exclusive $diff = $date2->diff($date1); echo $diff;

Something like this should work for you:

<?php

    $_POST['from_date'] = "2014-10-01";
    $_POST['to_date'] = "2014-11-02";

    $fromdate = $_POST['from_date'];
    $todate = $_POST['to_date'];

    $diff = abs(strtotime($fromdate) - strtotime($todate));

    $years = floor($diff / (365*60*60*24));
    $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
    $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

    printf("%d years, %d months, %d days
", $years, $months, $days);

?>

Output:

0 years, 1 months, 2 days