php在某两个时间之间的关系,PHP找到两个日期时间之间的差异

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(结果)字符串与必要的分隔符连接以符合请求的日期时间格式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值