试图用PHP定义我自己的时间类型


Trying to define my own time type in PHP

所以我正在尝试定义一个时间类型,但我不太确定如何定义。我在网上找到的答案给出了用当前时间定义时间类型的例子(即日期("h:I:sa")),但我正试图定义一个硬编码版本。我想要的格式是(HH:mm:ss)(小时:分钟:秒)我之所以需要将变量声明为时间类型,是为了以后可以使用它们进行比较。

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

使用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

PHP DateTime类就是您所需要的。

//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";