【问题标题】:PHP Time between two times两次之间的 PHP 时间
【发布时间】:2014-04-22 19:01:46
【问题描述】:

我正在尝试获取一些代码来检测当前时间之间的时间值对。我正在使用的代码如下。但是,即使当前时间属于某个范围,我也会不断收到“不匹配”。不知道哪里出错了。

//GET CURRENT TIME
$tz_object = new DateTimeZone('America/New_York');
$current_time = new DateTime();
$current_time->setTimezone($tz_object);

//SET TIME RANGE PAIRS
$time1Start = '08:00:00';
$time1End = '16:59:59';
$time2Start = '17:00:00';
$time2End = '07:59:59';

//FORMAT TIMES
$current_time = DateTime::createFromFormat('H:i:s', $current_time);
$time1Start = DateTime::createFromFormat('H:i:s', $time1Start);
$time1End = DateTime::createFromFormat('H:i:s', $time1End);
$time2Start = DateTime::createFromFormat('H:i:s', $time2Start);
$time2End = DateTime::createFromFormat('H:i:s', $time2End);

//TIME 1 SLOT
if ($current_time >= $time1Start && $current_time <= $time1End)
    {
        echo 'RANGE 1';
    }
//TIME 2 SLOT   
elseif ($current_time >= $time2Start && $current_time <= $time2End)
    {
        echo 'RANGE 2';
    }
else
    {
        echo 'NO MATCH';
    }

**更新**

因此,当我开始使用时区转换时,这似乎开始失败了。如果我传递一个原始时间值,它工作正常。但是,当我看到这一点时,我认为我的做法过于复杂了。本质上,我只需要确定当前时间是否在两个值之间。就我而言,我不关心今天、明天、昨天等。我只需要知道 16:42 是在 08:00 和 15:00 之间还是在 15:01 和 07:59 之间。这对我来说似乎很简单,但无论我如何简化它,我都无法让代码实现工作。

【问题讨论】:

  • $current_time = DateTime::... 的意义何在? $current_time 是 ALREADY 一个日期时间对象...
  • 您的结束时间早于时间 2 的开始时间,因此永远不会匹配。
  • Works for me(稍作清理,不会影响结果)
  • @JohnConde 谢谢!太奇怪了-我什至将您的代码复制并粘贴到我的页面中进行尝试,但我仍然得到相同的结果(不匹配)。奇怪 - 我会继续玩。
  • 首先验证“current_time”的日期和时间是否符合您的预期 (echo $current_time-&gt;format('Y-m-d H:i:s') )

标签: php datetime time


【解决方案1】:

你可以很容易地检查而不是你的代码,

if(date('H:i:s') == $your_time){
 //your code;
}

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多