【问题标题】:DateTime comparison not working PHP [duplicate]DateTime比较不起作用PHP [重复]
【发布时间】:2023-03-28 08:40:01
【问题描述】:

如果动态传递,时间比较不会起作用

$date = new DateTime();
    $date->setTimezone(new DateTimeZone('America/New_York'));                                  
    $myTime =$date->format('H:i');
    $myDay =$date->format('l');
if(($s<=$myTime) && ($e>=$myTime||$e=="00:00")) 
  {$open =1;}

如果硬编码,以下工作

if(("11:30"<="05:39")&&("23:00">="05:39"||"23:00"=="00:00"))
      {$open =1;}

我哪里出错了

【问题讨论】:

  • $open 在这些例子中永远不会是 1
  • 如果使用第一个而不是硬编码,它总是“1”

标签: php string datetime time


【解决方案1】:
// your first date  
$dateA = '2008-03-01 13:34'; 
// your second date 
$dateB = '2007-04-14 15:23'; 
if(strtotime($dateA) > strtotime($dateB)){ 
   // something here
}

【讨论】:

  • m 只使用时间格式 (H:i)
  • 将时间转换为秒,然后使用 strtotime 比较两次。
  • 不需要转换成秒 strtotime 就可以了。
  • strttotime 会将时间转换为秒。我只是告诉使用该函数来转换您的时间。
【解决方案2】:

首先,您使用字符串来比较时间。使用 strtotime (http://php.net/manual/en/function.strtotime.php) 或 mktime(http://php.net/manual/en/function.mktime.php) 或使用 DateTime 类 (http://php.net/manual/en/class.datetime.php) 转换为时间戳。比较字符串时,它们不是作为时间进行比较,而是作为字符序列进行比较。

【讨论】:

  • 你能提供工作示例吗
  • 您将在 php 手册页上有很多示例,只需向下滚动即可。
猜你喜欢
  • 2017-06-20
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 1970-01-01
相关资源
最近更新 更多