PHP-计算两个日期之间的差异


PHP - Calculate the difference between two dates

我想计算两个日期之间的年数。其中一个是从数据库中检索的,而另一个是以日期格式从用户输入中获取的。

我用这个代码从用户那里获得日期:

$today   = $_POST['to-day'];
$tomonth = $_POST['to-month'];
$toyaer  = $_POST['to-year'];
$dateto  = date("$toyaer-$tomonth-$today");

下面是我如何用从数据库中检索到的来计算的

$start      = $leaveresult['date']; // i took from database 
$end        = strtotime($dateto);   
$difference = abs($end - $start);
$years      = floor($difference / (60*60*24*365));

问题是我得到的结果总是0

我尝试了不同的方法,但所有的方法都得到了0,其中一个方法得到了大量的结果。

这是未经测试的,但我认为这样的东西会起作用:

$today = $_POST['to-day'];
$tomonth = $_POST['to-month'];
$toyear = $_POST['to-year'];
$dateto = "$toyear-$tomonth-$today";
$start = $leaveresult['date'];// i took from database 
$end = strtotime($dateto);   
$difference = abs($end - $start);
$years = floor($difference / (60*60*24*365));

我假设$leaveresult['date']是unix时间戳

另外请注意,我修复了后变量名称。

如果开始日期不在unix时间戳中,则使用

$start = strtotime($leaveresult['date']);// i took from database 

DateTime类通过给您一个diff方法简化了这一切。这将返回一个DateInterval对象,您可以从中获取要查找的值。

假设$_POST看起来像这样:

$_POST = array(
    'to-year' => 2010,
    'to-month' => 8,
    'to-day' => 22
);

$leaveresult['date']看起来是这样的:

$leaveresult = array(
    'date' => date('Y-m-d H:i:s', strtotime('-5 years')));

你可以这样做。。。

$input_date = new DateTime(sprintf("%d-%d-%d", $_POST['to-year'], $_POST['to-month'], $_POST['to-day']));
$database_date = new DateTime($leaveresult['date']);
$diff = $database_date->diff($input_date);
echo $diff->format('%r%y years') . PHP_EOL;
echo $diff->format('%r%m months') . PHP_EOL;
echo $diff->format('%r%d days') . PHP_EOL;
$years = $diff->y;

这将产生

3 years
1 months
5 days  

并且$years将等于3

在这两种情况下,您都需要一个时间戳-您格式化的时间戳(作为日期对象)和从数据库中获得的时间戳。。。所以我认为你的方法没有错,如果你在这两种情况下都得到了时间戳。。。但最后你试着用floor把数字四舍五入。。。当然,如果不到一年,这将导致0。先测试一下,不要四舍五入,然后测试一下你的时间戳,也许也出了问题?