将日期时间字符串转换为日期时间对象,returns 布尔值而不是对象

convert DateTime String to DateTime Object, returns boolean instead of object

编辑:@RiggsFolly 帮助解决了这个问题,我使用的日期时间格式是 H:i:00 而不是 H:i:s .

我需要比较许可证的注册日期和到期日期,我将这两个日期都作为字符串存储在 ssms 中,然后将它们作为字符串检索,当我想比较两者时,我尝试将两者都转换为 DateTime 对象,所以我可以使用 date_diff() 比较它们,但出于某种原因我只能将到期日期转换为对象,注册日期始终 returns 布尔值。

所以我的代码的工作方式是,它首先检查 $expirydate 是否为空,如果不是,那么它将进入条件并创建 $datetime 作为 DateTime 对象,然后创建 var $datetime1 转换 $registrationdate 并存储它,并创建 var $datetime2$expirydate 做同样的事情。在那之后,如果日期没有返回 false,那么它将使用 date_diff() 相互比较,然后创建 var $validityperiod 以将 2 个日期之间的天数差异存储在 positive/negative 整数中,例如+30 或 -3,它将用于显示用户还有多少天他们的许可证到期。

我很困惑为什么两者都是字符串值,但只有一个可以转换为 DateTime 对象而另一个 returns 布尔值?

我尝试了 3 个选项来将 DateTime 字符串转换为 DateTime 对象:

  1. date_create() 但它也是 returns 布尔值,用于注册和到期日期。

  2. date_create_from_format(),结果同上,都是returns boolean.

  3. 创建一个new DateTime()对象并使用createFromFormat()将其转换为DateTime对象,但它只对到期日有效,对注册日期无效,这是最接近的我可以得到,因为它至少可以将到期日期转换为 DateTime 对象。

    //the string values from my db is:
    // $registrationdate= "13/06/2019 15:06:06";
    // $expirydate="14/06/2019 16:46:00";

    //this example uses the third option
    if ($expirydate != null || $expirydate != ''){
        // creates DateTime objects 
        $datetime = new DateTime();
        //the line below is the problem, it cant convert the string to object
        $datetime1 = $datetime->createFromFormat('d/m/Y H:i:00', $registrationdate); 
        //however, this line below works, although both are strings
        $datetime2 = $datetime->createFromFormat('d/m/Y H:i:00', $expirydate); 

        if ($datetime1!= false && $datetime2 != false){
            // calculates the difference between DateTime objects 
            $interval = date_diff($datetime1, $datetime2);  

            // printing result in days format 
            $validityperiod= $interval->format('%r%a'); 
        }
        else $validityperiod = "";
    }

每次从字符串到对象returns布尔值的转换,都会returns出现如下错误:

Warning: date_format() expects parameter 1 to be DateTimeInterface, boolean given

如果它可以将注册日期转换为 DateTime 对象,那么它应该可以 运行 date_diff() 并且 $validityperiod 应该存储两个日期之间的天数差异

您必须在

中使用正确的格式
$datetime->createFromFormat('d/m/Y H:i:00', $expirydate); 

第二个是偶然工作的,因为你的时间实际上在 00 秒后结束,所以格式匹配,即

$expirydate="14/06/2019 16:46:00";`
                // ---        ^^ 

但是第一个日期与格式 :00 不匹配,因为它有一个 06 作为秒数,即

$registrationdate= "13/06/2019 15:06:06";`
      //  -----------                ^^

因此,对两者都使用正确的格式 'd/m/Y H:i:s',您将获得正确的创建日期。