【问题标题】:Compare Datetime objects php比较日期时间对象 php
【发布时间】:2017-07-24 16:30:40
【问题描述】:

我必须将 datetime 对象与 php 进行比较,$availability 是一个日期数组,其中包含(从:2017-07-24 16:20:08.0000002017-07-25 16:20:08.000000)以及何时是 2017-07-23 16:20:08.000000

/// when : 2017-07-23
$when = DateTime::createFromFormat( 'Y-m-d', '2017-07-23' );
// from : 2017-07-24 
$from = DateTime::createFromFormat( 'Y-m-d', '2017-07-24' );
// to : 2017-07-25 
$to   = DateTime::createFromFormat( 'Y-m-d', '2017-07-25' );
if ( $when >= $from && $when <= $to ) { echo $when . "is between from and to"; }

这不起作用,还是我错过了什么?

如何比较来自DateTime::createFromFormat 的对象?有可能吗,还是我必须strtotime

【问题讨论】:

  • 解释“不起作用”....你的意思是它显示中间消息?
  • $when 是 23 号,小于 $from 24 号。所以第一个条件$when &gt;= $from 立即失败。此外,您不能echo $when; - 它是一个对象,而不是一个字符串。回显时需要使用$when-&gt;format("Y-m-d")
  • echo $when 也会得到类似Object of class DateTime could not be converted to string use $when-&gt;format('YYYY-mm-dd')的错误
  • 也许你应该首先在你的文件顶部添加error reporting到你的文件顶部测试时在你打开PHP标签之后,例如&lt;?php error_reporting(E_ALL); ini_set('display_errors', 1);,看看它是否产生任何东西。
  • @Mark Ba​​ker,这意味着它不显示中间消息。 @RiggsFolly,你是对的,我当然累了,我没有找到那个 23 大声笑,谢谢你指出这一点。

标签: php datetime


【解决方案1】:

一些问题:

1) 给定输入条件将失败。具体来说,您的 $when 对象在您的 $from 对象之前拥有一个时间(前一天)。所以,$when &gt;= $from 在 if 语句中失败了。

2) if 语句块中的代码会出错。 DateTime::createFromFormat() 方法创建的变量是 DateTime objects。您不能回显一个对象,它必须转换为字符串,这可以通过使用 DateTime 类的 format 方法来完成。所以将 if 块中的代码重写为:

echo "{$when->format('Y-m-d')} is between {$from->format('Y-m-d')} and {$to->format('Y-m-d')}";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多