尝试在PHP中定义我自己的时间类型 [英] Trying to define my own time type in PHP
本文介绍了尝试在PHP中定义我自己的时间类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<?php
$ my_time = '10:00:00';
$ your_time = '11:00:00';
if($ my_time> $ your_time){
echoYou less time;
}
?>
解决方案
PHP DateTime类是您需要的。 p>
//实例化一个DateTime对象
$ time = new DateTime();
//使用DateTime obj创建两个新的DateTime对象
$ yourTime = $ time-> createFromFormat('h:i:s','12:30:30') ; //第三个参数可以定义tz
$ theirTime = $ time-> createFromFormat('h:i:s','12:10:15');
//使用diff()返回DateInterval
$ dateInterval = $ yourTime-> diff($ theirTime);
//将DateInterval格式化为字符串
$ differenceBetweenYoursAndTheirs = $ dateInterval->格式('%h:%i:%s');
//用你的间隔做一些事
echo{yourTime->格式('h:i:s')}和{$ theirTime->格式'h:i:s')}是$ differenceBetweenYoursAndTheirs;
So I am trying to define a time type and I am not quite sure how to do it. The answers I find online give examples of defining a time type with the current time (i.e date("h:i:sa")) however I am trying to define a hard coded version.The format I want is (HH:mm:ss) (hour:minutes:seconds) The reason why I need the variable to be declared as time type is so that they can be used later on to be compared.
<?php
$my_time = '10:00:00';
$your_time = '11:00:00';
if($my_time > $your_time){
echo "You have less time";
}
?>
解决方案
The PHP DateTime Class is what you need.
//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";
这篇关于尝试在PHP中定义我自己的时间类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文