得到两个给定时间之间的时间差 [英] get the difference in time between two given time

查看:64
本文介绍了得到两个给定时间之间的时间差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取两个给定时间之间的时间差,例如第一次是"17:00:01",然后是第二次"17:47:25",这是我到目前为止所尝试的,

I'm trying to get the difference in time between two given times e.g. first time '17:00:01' and then second time '17:47:25' and here's what I tried so far,

$start_time = "17:00:01";
$end_time = "17:47:25";

echo $start_time->diff($end_time);

但是不幸的是,似乎没有用,请帮忙,有什么主意吗?

But seem's unfortunately not working, any help, ideas please?

我的预期输出必须是,如果小时数没有差异,但分钟和秒之间存在差异,则为"22分钟15秒";如果分钟数无差异但小时数之间存在差异,则为"2小时10秒" ,但如果相差只有几秒钟,则为"22秒".

My expected output must be like, if no difference in hours but there's difference in minutes and seconds then, "22 mins and 15 secs", If no difference in minutes but have difference in hours then, "2 hrs and 10 secs" but if only seconds in difference then, "22 secs".

推荐答案

php中的字符串不是对象,因此无法在其上调用diff方法.

String in php is not object, so can't call diff method on it.

使用diff方法,必须将字符串更改为DateTime对象.

Use diff method, you must change the string to DateTime object.

如果要比较同一天的时差,可以尝试:

If you want to compare time difference in same day, you could try:

$start_time = "17:00:01";
$end_time = "17:47:25";

$start_datetime = new DateTime(date('Y-m-d').' '.$start_time);
$end_datetime = new DateTime(date('Y-m-d').' '.$end_time);

var_dump($start_datetime->diff($end_datetime));

这篇关于得到两个给定时间之间的时间差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆