Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用PHP计算两个日期之间的时间差?_Php_Date_Datetime_Time - Fatal编程技术网

如何使用PHP计算两个日期之间的时间差?

如何使用PHP计算两个日期之间的时间差?,php,date,datetime,time,Php,Date,Datetime,Time,我在表格上有两次约会 Start Date: 2015-11-15 11:40:44pm End Date: 2015-11-22 10:50:88am 现在我需要通过以下形式找出这两者之间的区别: 0 years, 0 months, 7 days, 22 hours, 44 mints, 35 sec 如何在PHP中实现这一点 我已经试过了: $strStart = date('Y-m-d h:i:s', time() - 3600); $strEnd = '2015-11-22

我在表格上有两次约会

Start Date: 2015-11-15 11:40:44pm 
End Date: 2015-11-22 10:50:88am
现在我需要通过以下形式找出这两者之间的区别:

0 years, 0 months, 7 days, 22 hours, 44 mints, 35 sec
如何在PHP中实现这一点

我已经试过了:

$strStart = date('Y-m-d h:i:s', time() - 3600);
$strEnd   = '2015-11-22 02:45:25';
$dteStart = new DateTime($strStart); 
$dteEnd   = new DateTime($strEnd);
$dteDiff  = $dteStart->diff($dteEnd);
echo $dteDiff->format("%H:%I:%S");
输出:22:53:58

输出未完全显示

$startDate = "2015-11-15 11:40:44pm";
$endDate = "2015-11-22 10:50:48am";  // You had 50:88 here? That's not an existing time

$startEpoch = strtotime($startDate);
$endEpoch = strtotime($endDate);

$difference = $endEpoch - $startEpoch;
上面的脚本将开始和结束日期转换为历元时间(自1970年1月1日00:00:00 GMT起的秒数)。然后它进行数学运算,得出它们之间的差异

由于年和月不是一个静态值,我没有在下面的脚本中添加它们

$minute = 60; // A minute in seconds
$hour = $minute * 60; // An hour in seconds
$day = $hour * 24; // A day in seconds

$daycount = 0; // Counts the days
$hourcount = 0; // Counts the hours
$minutecount = 0; // Counts the minutes

while ($difference > $day) { // While the difference is still bigger than a day
    $difference -= $day; // Takes 1 day from the difference
    $daycount += 1; // Add 1 to days
}

// Now it continues with what's left
while ($difference > $hour) { // While the difference is still bigger than an hour
    $difference -= $hour; // Takes 1 hour from the difference
    $hourcount += 1; // Add 1 to hours
}

// Now it continues with what's left
while ($difference > $minute) { // While the difference is still bigger than a minute
    $difference -= $minute; // Takes 1 minute from the difference
    $minutecount += 1; // Add 1 to minutes
}

// What remains are the seconds
echo $daycount . " days ";
echo $hourcount . " hours ";
echo $minutecount . " minutes ";
echo $difference . " seconds ";
现在我需要通过以下形式找出这两者之间的区别:

0 years, 0 months, 7 days, 22 hours, 44 mints, 35 sec
0年0月7天22小时44分钟35秒

这就是你的主要问题,得到这个精确的输出结构

那么你只需要换一种方式:

echo $dteDiff->format("%y years, %m months, %d days, %h hours, %i mints, %s sec");

你试过什么?至少试试php的一些datetime函数,如果失败了,我们可以帮助您解决失败的代码。