试图在PHP中定义自己的时间类型

时间:2016-03-25 06:36:00

标签: php time format

所以我试图定义一个时间类型,我不太清楚如何做到这一点。我在网上找到的答案提供了使用当前时间定义时间类型的示例(即日期(“h:i:sa”))但是我正在尝试定义硬编码版本。格式I想要是(HH:mm:ss)(小时:分钟:秒)我需要将变量声明为时间类型的原因是为了以后可以将它们用于比较。< / p>

<?php 
$my_time = '10:00:00';
$your_time = '11:00:00';
if($my_time > $your_time){
echo "You have less time";
}
?>

2 个答案:

答案 0 :(得分:3)

使用 DateTime 创建正确的对象,然后您可以使用标准比较运算符。

$my_time   = DateTime::createFromFormat('H:i:s', '10:00:00');
$your_time = DateTime::createFromFormat('H:i:s', '11:00:00');
var_dump($my_time > $your_time);

<强> Fiddle

答案 1 :(得分:1)

PHP DateTime Class就是您所需要的。

//instantiate a DateTime Object      
$time = new DateTime();

//Use the DateTime obj to create two new DateTime objects
$yourTime = $time->createFromFormat('h:i:s', '12:30:30'); //third param here can define tz
$theirTime = $time->createFromFormat('h:i:s', '12:10:15');

//Use diff() to return a DateInterval
$dateInterval = $yourTime->diff($theirTime);

//Format the DateInterval as a string
$differenceBetweenYoursAndTheirs = $dateInterval->format('%h:%i:%s');

//Do something with your interval
echo "The difference between {$yourTime->format('h:i:s')} and {$theirTime->format('h:i:s')} is $differenceBetweenYoursAndTheirs";