John Conde在他的方法中执行了所有正确的程序,但不满足您的问题的最后一步,即将结果格式化为您的规范。
此代码(演示)将显示原始差异,尝试立即格式化原始差异,显示我的准备步骤,最后呈现正确格式化的结果,从而暴露出麻烦:
$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
输出:
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
现在解释我的日期时间值准备:
$details获取diff对象并将其转换为数组。 array_flip(['y','m','d','h','i','s'])创建一个键数组,用于从(array)$diff使用array_intersect_key()中删除所有不相关的键。
然后使用array_map()我的方法迭代每个值并键入$details,使用0's 将其左侧填充到适当的长度,并将$r(结果)字符串与必要的分隔符连接以符合请求的日期时间格式。