获取时差 [英] Get time difference

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

问题描述

如何计算PHP中的时差?

How can I compute time difference in PHP?

示例:2:00和3:30.

example: 2:00 and 3:30.

我想将时间转换为秒,然后减去它们,然后将其转换回小时和分钟,以了解两者之间的差异.有没有更简单的方法来获得不同?

I want to convert the time to seconds then subtract them then convert it back to hours and minutes to know the difference. Is there an easier way to get the difference?

推荐答案

查看 PHP DateTime对象.

$dateA = new DateTime('2:00');
$dateB = new DateTime('3:00');

$difference = $dateA->diff($dateB);

(假设您有> = PHP 5.3)

(assuming you have >= PHP 5.3)

您也可以按照程序的方式进行操作...

You can also do it the procedural way...

$dateA = strtotime('2:00');
$dateB = strtotime('3:00');

$difference = $dateB - $dateA;

在CodePad.org上查看.

您可以像这样获得小时偏移量...

You can get the hour offset like so...

$hours = $difference / 3600;

如果您要处理的时间介于24小时之间(0:00-23:59),那么您也可以...

If you are dealing with times that fall between a 24 hour period (0:00 - 23:59), you could also do...

$hours = (int) date('g', $difference);

尽管那可能太不灵活了,不值得实施.

Though that is probably too inflexible to be worth implementing.

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

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