PHP查找两个日期时间之间的差异

时间:2022-06-08 21:30:10

I'm trying to get the difference between two datetimes and return it as a datetime. I've found examples using diff but i can't seem to get it right.

我试图得到两个datetimes之间的差异,并将它作为一个datetime返回。我已经找到了一些使用diff的例子,但是我似乎做得不对。

$timein = date("Y-m-d H:i:s");
$timeout = date("Y-m-d 20:00:00");
$totaltime = $timein->diff($timeout);

However $totaltime logs "0000-00-00 00:00:00" to my DB. Is this because i'm not formatting my totaltime variable?

但是$totaltime记录“000000 -00 00:00”到我的数据库。这是因为我没有格式化我的totaltime变量吗?

5 个解决方案

#1


38  

I'm not sure what format you're looking for in your difference but here's how to do it using DateTime

我不确定您想要的格式与您的不同,但这里是如何使用DateTime来实现的

$datetime1 = new DateTime();
$datetime2 = new DateTime('2011-01-03 17:13:00');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
echo $elapsed;

#2


1  

You can simply use datetime diff and format for calculating difference.

您可以简单地使用datetime diff和format来计算差异。

<?php
$datetime1 = new DateTime('2009-10-11 12:12:00');
$datetime2 = new DateTime('2009-10-13 10:12:00');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%Y-%m-%d %H:%i:%s');
?>

For more information OF DATETIME format, refer: here
You can change the interval format in the way,you want.

有关DATETIME格式的更多信息,请参见:这里您可以更改方式中的间隔格式,您需要。

Here is the working example

下面是一个工作示例

P.S. These features( diff() and format()) work with >=PHP 5.3.0 only

这些特性(diff()和format())只适用于>=PHP 5.3.0

#3


0  

John Conde does all the right procedures in his method but doesn't satisfy the final step in your question which is to format the result to your specifications.

John Conde在他的方法中做了所有正确的步骤,但是不满足您问题中的最后一步,即根据您的规范格式化结果。

This code (Demo) will display the raw difference, expose the trouble with trying to immediately format the raw difference, display my preparation steps, and finally present the correctly formatted result:

这段代码(Demo)将显示原始差异,暴露尝试立即格式化原始差异的麻烦,显示我的准备步骤,最后显示正确格式化的结果:

$datetime1 = new DateTime('2017-04-26 18:13:06');
$datetime2 = new DateTime('2011-01-17 17:13:00');  // change the millenium to see output difference
$diff = $datetime1->diff($datetime2);

// this will get you very close, but it will not pad the digits to conform with your expected format
echo "Raw Difference: ",$diff->format('%y years %m months %d days %h hours %i minutes %s seconds'),"\n";

// Notice the impact when you change $datetime2's millenium from '1' to '2'
echo "Invalid format: ",$diff->format('%Y-%m-%d %H:%i:%s'),"\n";  // only H does it right

$details=array_intersect_key((array)$diff,array_flip(['y','m','d','h','i','s']));

echo '$detail array: ';
var_export($details);
echo "\n";

array_map(function($v,$k)
    use(&$r)
    {
        $r.=($k=='y'?str_pad($v,4,"0",STR_PAD_LEFT):str_pad($v,2,"0",STR_PAD_LEFT));
        if($k=='y' || $k=='m'){$r.="-";}
        elseif($k=='d'){$r.=" ";}
        elseif($k=='h' || $k=='i'){$r.=":";}
    },$details,array_keys($details)
);
echo "Valid format: ",$r; // now all components of datetime are properly padded

Output:

输出:

Raw Difference: 6 years 3 months 9 days 1 hours 0 minutes 6 seconds
Invalid format: 06-3-9 01:0:6
$detail array: array (
  'y' => 6,
  'm' => 3,
  'd' => 9,
  'h' => 1,
  'i' => 0,
  's' => 6,
)
Valid format: 0006-03-09 01:00:06

Now to explain my datetime value preparation:

现在来解释我的datetime值准备:

$details takes the diff object and casts it as an array. array_flip(['y','m','d','h','i','s']) creates an array of keys which will be used to remove all irrelevant keys from (array)$diff using array_intersect_key().

$details接受diff对象并将其转换为数组。array_flip(['y','m','d','h','i','s')创建一个键数组,该数组将使用array_intersect_key()从$diff中删除所有不相关的键。

Then using array_map() my method iterates each value and key in $details, pads its left side to the appropriate length with 0's, and concatenates the $r (result) string with the necessary separators to conform with requested datetime format.

然后使用array_map(),我的方法在$details中迭代每个值和键,用0将其左侧填充到适当的长度,并将$r (result)字符串与必要的分隔符连接起来,以符合请求的datetime格式。

#4


-1  

<?php
$value='20140203113405';
$val='20150203113410';

$val1=str_split($val,2);
$dateval1=$val1[0].$val1[1]."-".$val1[2]."-".$val1[3];
$timeval1=$val1[4].":".$val1[5].":".$val1[6];

$val2=str_split($value,2);
$dateval2=$val2[0].$val2[1]."-".$val2[2]."-".$val2[3];
$timeval2=$val2[4].":".$val2[5].":".$val2[6];

$date1=new DateTime($dateval1);
$date2=new DateTime($dateval2);
$diffdate=date_diff($date1,$date2);
$dates=$diffdate->format("%a days");
$difftime = strtotime($timeval1) - strtotime($timeval2);
echo $dates;
echo $difftime."seconds";
?>

#5


-1  

<?php
$val1 = '2014-04-10 11:34:09';
$val2 = '2015-04-10 10:56:15';
$result1 = (explode(' ', $val1)) ;
$result2 = (explode(' ', $val2)) ;
$date1= new DateTime($result1[0]);
$date2=new DateTime($result2[0]);
$diffdate=date_diff($date1,$date2);
$difftime = strtotime($result1[1]) - strtotime($result2[1]);
$dates=$diffdate->format("%R%a days");
echo $dates;
echo $difftime;
?>

#1


38  

I'm not sure what format you're looking for in your difference but here's how to do it using DateTime

我不确定您想要的格式与您的不同,但这里是如何使用DateTime来实现的

$datetime1 = new DateTime();
$datetime2 = new DateTime('2011-01-03 17:13:00');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
echo $elapsed;

#2


1  

You can simply use datetime diff and format for calculating difference.

您可以简单地使用datetime diff和format来计算差异。

<?php
$datetime1 = new DateTime('2009-10-11 12:12:00');
$datetime2 = new DateTime('2009-10-13 10:12:00');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%Y-%m-%d %H:%i:%s');
?>

For more information OF DATETIME format, refer: here
You can change the interval format in the way,you want.

有关DATETIME格式的更多信息,请参见:这里您可以更改方式中的间隔格式,您需要。

Here is the working example

下面是一个工作示例

P.S. These features( diff() and format()) work with >=PHP 5.3.0 only

这些特性(diff()和format())只适用于>=PHP 5.3.0

#3


0  

John Conde does all the right procedures in his method but doesn't satisfy the final step in your question which is to format the result to your specifications.

John Conde在他的方法中做了所有正确的步骤,但是不满足您问题中的最后一步,即根据您的规范格式化结果。

This code (Demo) will display the raw difference, expose the trouble with trying to immediately format the raw difference, display my preparation steps, and finally present the correctly formatted result:

这段代码(Demo)将显示原始差异,暴露尝试立即格式化原始差异的麻烦,显示我的准备步骤,最后显示正确格式化的结果:

$datetime1 = new DateTime('2017-04-26 18:13:06');
$datetime2 = new DateTime('2011-01-17 17:13:00');  // change the millenium to see output difference
$diff = $datetime1->diff($datetime2);

// this will get you very close, but it will not pad the digits to conform with your expected format
echo "Raw Difference: ",$diff->format('%y years %m months %d days %h hours %i minutes %s seconds'),"\n";

// Notice the impact when you change $datetime2's millenium from '1' to '2'
echo "Invalid format: ",$diff->format('%Y-%m-%d %H:%i:%s'),"\n";  // only H does it right

$details=array_intersect_key((array)$diff,array_flip(['y','m','d','h','i','s']));

echo '$detail array: ';
var_export($details);
echo "\n";

array_map(function($v,$k)
    use(&$r)
    {
        $r.=($k=='y'?str_pad($v,4,"0",STR_PAD_LEFT):str_pad($v,2,"0",STR_PAD_LEFT));
        if($k=='y' || $k=='m'){$r.="-";}
        elseif($k=='d'){$r.=" ";}
        elseif($k=='h' || $k=='i'){$r.=":";}
    },$details,array_keys($details)
);
echo "Valid format: ",$r; // now all components of datetime are properly padded

Output:

输出:

Raw Difference: 6 years 3 months 9 days 1 hours 0 minutes 6 seconds
Invalid format: 06-3-9 01:0:6
$detail array: array (
  'y' => 6,
  'm' => 3,
  'd' => 9,
  'h' => 1,
  'i' => 0,
  's' => 6,
)
Valid format: 0006-03-09 01:00:06

Now to explain my datetime value preparation:

现在来解释我的datetime值准备:

$details takes the diff object and casts it as an array. array_flip(['y','m','d','h','i','s']) creates an array of keys which will be used to remove all irrelevant keys from (array)$diff using array_intersect_key().

$details接受diff对象并将其转换为数组。array_flip(['y','m','d','h','i','s')创建一个键数组,该数组将使用array_intersect_key()从$diff中删除所有不相关的键。

Then using array_map() my method iterates each value and key in $details, pads its left side to the appropriate length with 0's, and concatenates the $r (result) string with the necessary separators to conform with requested datetime format.

然后使用array_map(),我的方法在$details中迭代每个值和键,用0将其左侧填充到适当的长度,并将$r (result)字符串与必要的分隔符连接起来,以符合请求的datetime格式。

#4


-1  

<?php
$value='20140203113405';
$val='20150203113410';

$val1=str_split($val,2);
$dateval1=$val1[0].$val1[1]."-".$val1[2]."-".$val1[3];
$timeval1=$val1[4].":".$val1[5].":".$val1[6];

$val2=str_split($value,2);
$dateval2=$val2[0].$val2[1]."-".$val2[2]."-".$val2[3];
$timeval2=$val2[4].":".$val2[5].":".$val2[6];

$date1=new DateTime($dateval1);
$date2=new DateTime($dateval2);
$diffdate=date_diff($date1,$date2);
$dates=$diffdate->format("%a days");
$difftime = strtotime($timeval1) - strtotime($timeval2);
echo $dates;
echo $difftime."seconds";
?>

#5


-1  

<?php
$val1 = '2014-04-10 11:34:09';
$val2 = '2015-04-10 10:56:15';
$result1 = (explode(' ', $val1)) ;
$result2 = (explode(' ', $val2)) ;
$date1= new DateTime($result1[0]);
$date2=new DateTime($result2[0]);
$diffdate=date_diff($date1,$date2);
$difftime = strtotime($result1[1]) - strtotime($result2[1]);
$dates=$diffdate->format("%R%a days");
echo $dates;
echo $difftime;
?>