【问题标题】:Trying to define my own time type in PHP试图在 PHP 中定义我自己的时间类型
【发布时间】:2016-07-12 22:18:38
【问题描述】:

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

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

【问题讨论】:

  • 该代码只是一个示例,让我了解我正在尝试做什么,我只想定义我自己的时间变量,它将用于与另一个时间对象进行比较后期

标签: php time format


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • @hankypanky 赢得比赛
    • 现在才看到,这个也很有用,谢谢。我对 DateTime 对象有了更好的理解
    猜你喜欢
    • 2013-10-15
    • 2014-10-07
    • 2012-02-27
    • 2016-07-15
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多