【问题标题】:Date & time comparison operators >= not showing dates that are equal日期和时间比较运算符 >= 不显示相等的日期
【发布时间】:2018-05-15 20:27:33
【问题描述】:

我试图展示今天或以后发生的事件,其中今天是特别有问题的。

public function getInspirationsMeetingIds()
{
    $ids = [];
    if (($inspirationMeetings = $this->getCustomField('meetings'))) {

        foreach ($inspirationMeetings as $meeting) {

            $row = new Inspiration($meeting['meeting']);

            $dateFrom = $row->getCustomField('date');

            if (strtotime($dateFrom) >= time()) {
                $ids[] = $row->getId();
            }

        }
    }
     return $ids;
}

由于某种原因,这只会显示大于 time() 的事件,而不是今天的事件,但是当我尝试这个时:

if (strtotime($dateFrom) <= time()) {
            $ids[] = $row->getId();
}

显示今天和以前的事件。

【问题讨论】:

  • 时间以秒为单位。您准确地击中第二个的机会非常渺茫
  • 可能是因为 time() 显示的是当前时间,而日期在 time() 之前有一个时间戳。
  • $dateFrom 是什么格式?
  • 我认为格式并不重要,因为 strtotime 总是会在一天中的某个时间丢失时添加它。 3v4l.org/cYKO4

标签: php datetime


【解决方案1】:

我认为您需要在 datefrom 中添加时间戳。

如果省略时间,Strtotime 将添加中午。
看这个例子https://3v4l.org/cYKO4

if (strtotime($dateFrom ) >= strtotime(date("Y-m-d 00:00"))) {

将使其显示所有日期来源

编辑在错误的一侧添加了 00:00

【讨论】:

  • 现在您使用的是date() 而不是time()?我告诉过你时间没有用。
  • 我确定。但是我忘记了strtotime
【解决方案2】:

使用 DateTime 类http://php.net/manual/en/class.datetime.php

time() 给出了自 1970 年 1 月 1 日以来的秒数。您精确到秒的机会非常小,因此几乎不会匹配。

相反,创建一个带有时间的日期。

$date = new DateTime($dateFrom); // or DateTime::createFromFormat($format, $dateFrom);
$today = new DateTime();

if ($date >= $today) {
   // should work
}

【讨论】:

  • 这不是问题。 time 和 strtotime 都以秒为单位显示时间。因为这是一个&gt;= 比较,所以不是“一秒钟”的问题
  • 他正在尝试匹配今天,但他正在与今天的特定秒进行比较。那是他的问题。任何大于都可以,但他的 = 部分有问题。
  • 恐怕你不正确。看。我为今天(上午 9 点)创建了一个时间并将其与 time() 进行比较。当然不是>=,它是less,因此不会匹配3v4l.org/82N2I
猜你喜欢
  • 2015-07-20
  • 2021-07-13
  • 2021-04-23
  • 1970-01-01
  • 2013-04-09
  • 2012-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多