我有两个表格日期:

Start Date: 2007-03-24 
End Date: 2009-06-26

现在我需要通过以下形式找到这两者之间的区别:

2 years, 3 months and 2 days

如何在PHP中执行此操作?


当前回答

我在PHP5.2中遇到了同样的问题,并用MySQL解决了这个问题。可能并不是你想要的,但这会奏效,并返回天数:

$datediff_q = $dbh->prepare("SELECT DATEDIFF(:date2, :date1)");
$datediff_q->bindValue(':date1', '2007-03-24', PDO::PARAM_STR);
$datediff_q->bindValue(':date2', '2009-06-26', PDO::PARAM_STR);
$datediff = ($datediff_q->execute()) ? $datediff_q->fetchColumn(0) : false;

此处有更多信息http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff

其他回答

// If you just want to see the year difference then use this function.
// Using the logic I've created you may also create month and day difference
// which I did not provide here so you may have the efforts to use your brain.
// :)
$date1='2009-01-01';
$date2='2010-01-01';
echo getYearDifference ($date1,$date2);
function getYearDifference($date1=strtotime($date1),$date2=strtotime($date2)){
    $year = 0;
    while($date2 > $date1 = strtotime('+1 year', $date1)){
        ++$year;
    }
    return $year;
}

我有一些简单的逻辑:

<?php
    per_days_diff('2011-12-12','2011-12-29')
    function per_days_diff($start_date, $end_date) {
        $per_days = 0;
        $noOfWeek = 0;
        $noOfWeekEnd = 0;
        $highSeason=array("7", "8");

        $current_date = strtotime($start_date);
        $current_date += (24 * 3600);
        $end_date = strtotime($end_date);

        $seassion = (in_array(date('m', $current_date), $highSeason))?"2":"1";

        $noOfdays = array('');

        while ($current_date <= $end_date) {
            if ($current_date <= $end_date) {
                $date = date('N', $current_date);
                array_push($noOfdays,$date);
                $current_date = strtotime('+1 day', $current_date);
            }
        }

        $finalDays = array_shift($noOfdays);
        //print_r($noOfdays);
        $weekFirst = array("week"=>array(),"weekEnd"=>array());
        for($i = 0; $i < count($noOfdays); $i++)
        {
            if ($noOfdays[$i] == 1)
            {
                //echo "This is week";
                //echo "<br/>";
                if($noOfdays[$i+6]==7)
                {
                    $noOfWeek++;
                    $i=$i+6;
                }
                else
                {
                    $per_days++;
                }
                //array_push($weekFirst["week"],$day);
            }
            else if($noOfdays[$i]==5)
            {
                //echo "This is weekend";
                //echo "<br/>";
                if($noOfdays[$i+2] ==7)
                {
                    $noOfWeekEnd++;
                    $i = $i+2;
                }
                else
                {
                    $per_days++;
                }
                //echo "After weekend value:- ".$i;
                //echo "<br/>";
            }
            else
            {
                $per_days++;
            }
        }

        /*echo $noOfWeek;
          echo "<br/>";
          echo $noOfWeekEnd;
          echo "<br/>";
          print_r($per_days);
          echo "<br/>";
          print_r($weekFirst);
        */

        $duration = array("weeks"=>$noOfWeek, "weekends"=>$noOfWeekEnd, "perDay"=>$per_days, "seassion"=>$seassion);
        return $duration;
      ?>

我更喜欢使用date_create和date_diff对象。

代码:

$date1 = date_create("2007-03-24");
$date2 = date_create("2009-06-26");

$dateDifference = date_diff($date1, $date2)->format('%y years, %m months and %d days');

echo $dateDifference;

输出:

2 years, 3 months and 2 days

有关更多信息,请阅读PHP date_diff手册

根据手册date_diff是的别名日期时间::diff()

您可以始终使用以下函数,以年和月为单位返回年龄(即1年4个月)

function getAge($dob, $age_at_date)
{  
    $d1 = new DateTime($dob);
    $d2 = new DateTime($age_at_date);
    $age = $d2->diff($d1);
    $years = $age->y;
    $months = $age->m;

    return $years.'.'.months;
}

或者如果希望在当前日期计算年龄,可以使用

function getAge($dob)
{  
    $d1 = new DateTime($dob);
    $d2 = new DateTime(date());
    $age = $d2->diff($d1);
    $years = $age->y;
    $months = $age->m;

    return $years.'.'.months;
}

我想带来一个稍微不同的视角,这似乎没有被提及。

你可以用声明的方式解决这个问题(就像任何其他问题一样)。重点是问你需要什么,而不是如何到达那里。

在这里,你需要与众不同。但这有什么不同?这是一个间隔,正如在最受欢迎的答案中所提到的。问题是如何获取它。您可以不显式调用diff()方法,而是按开始日期和结束日期创建一个间隔,即按日期范围:

$startDate = '2007-03-24';
$endDate = '2009-06-26';
$range = new FromRange(new ISO8601DateTime($startDate), new ISO8601DateTime($endDate));

所有诸如闰年之类的复杂问题都已经解决了。现在,当您有一个固定开始日期时间的间隔时,您可以获得一个人类可读的版本:

var_dump((new HumanReadable($range))->value());

它输出的正是你所需要的。

如果您需要一些自定义格式,这也不是问题。您可以使用ISO8601格式化类,该类接受具有六个参数的调用:年、月、日、小时、分钟和秒:

(new ISO8601Formatted(
    new FromRange(
        new ISO8601DateTime('2017-07-03T14:27:39+00:00'),
        new ISO8601DateTime('2018-07-05T14:27:39.235487+00:00')
    ),
    function (int $years, int $months, int $days, int $hours, int $minutes, int $seconds) {
        return $years >= 1 ? 'More than a year' : 'Less than a year';
    }
))
    ->value();

它的产量超过一年。

有关此方法的更多信息,请查看快速入门条目。