PHP 致命错误:未捕获的错误:调用字符串中的成员函数 diff()

Posted

技术标签:

【中文标题】PHP 致命错误:未捕获的错误:调用字符串中的成员函数 diff()【英文标题】:PHP Fatal error: Uncaught Error: Call to a member function diff() on string in 【发布时间】:2022-01-20 21:01:11 【问题描述】:

我将订单日期时间存储在 mysql 数据库中。 我明白了。现在我将其转换为用户本地时区,然后在其中添加 1 天。

现在我要做的是与用户当前的本地时间相比,在上述日期时间还剩下多少小时和分钟。我的代码如下所示

$timestamp_pending_accept = strtotime($pending_accept_row['order_time']);
$order_expiry_date = date('Y-m-d H:i:s', strtotime('+1 day', $timestamp_pending_accept));
$local_time = convert_timezone($order_expiry_date,$_SESSION['user_timezone'],SERVER_TIMEZONE);
$datetime = new DateTime();
$timezone = new DateTimeZone($_SESSION['user_timezone']);
$datetime->setTimezone($timezone);
$now = $datetime->format('Y-m-d H:i:s');
$interval = $order_expiry_date->diff($now);
$remaining_time = $interval->format("%h h, %i m");
echo $remaining_time;

但它给我的错误叫

php Fatal error:  Uncaught Error: Call to a member function diff() on string in

我不知道如何解决这个问题,请告诉我这里是否有人可以帮助我做同样的事情。

谢谢!

【问题讨论】:

错误很明显,因为$order_expiry_date是一个字符串而不是一个DateTime对象 【参考方案1】:

致命错误出现在这一行:

<?php
$interval = $order_expiry_date->diff($now);

表示你尝试调用objectdiff方法,但是$order_expiry_date的类型是string

在行前添加调试语句以确保:

<?php 
var_dump($order_expiry_date);exit;
$interval = $order_expiry_date->diff($now);

它应该输出类似string(19) "2021-06-26 15:55:32"的东西。

要修复错误,您应该执行一些步骤:

    $order_expiry_date从字符串转换为DateTime对象。 用 Datetime 对象替换 $now 参数(它的类型也是字符串)

结果如下:

<?php
/* region for demonstration */
$pending_accept_row['order_time'] = '2021-06-25 15:55:32';

$_SESSION['user_timezone'] = 'UTC';
define('SERVER_TIMEZONE', 'UTC');

function convert_timezone($date, $user_timezone, $server_timezone) 
  return $date;

/* endregion */

$timestamp_pending_accept = strtotime($pending_accept_row['order_time']);
$order_expiry_date = date('Y-m-d H:i:s', strtotime('+1 day', $timestamp_pending_accept));
$local_time = convert_timezone($order_expiry_date,$_SESSION['user_timezone'],SERVER_TIMEZONE);
$datetime = new DateTime();
$timezone = new DateTimeZone($_SESSION['user_timezone']);
$datetime->setTimezone($timezone);
// no need to convert DateTime to string
// $now = $datetime->format('Y-m-d H:i:s');

$order_expiry_date = DateTime::createFromFormat('Y-m-d H:i:s', $order_expiry_date);
// $interval = $order_expiry_date->diff($now);
$interval = $order_expiry_date->diff($datetime);
$remaining_time = $interval->format("%h h, %i m");
echo $remaining_time;

Live demo on PHP sandbox.

【讨论】:

非常感谢先生!它解决了我的问题!

以上是关于PHP 致命错误:未捕获的错误:调用字符串中的成员函数 diff()的主要内容,如果未能解决你的问题,请参考以下文章

致命错误:未捕获的错误:在 null 上调用成员函数 select()

PHP“致命错误:未捕获错误:调用成员函数prepare()为null”

PHP:致命错误:未捕获的错误:在布尔值上调用成员函数 execute() [重复]

致命错误:未捕获的错误:调用成员函数 find() PHP simple_html_dom_parser [重复]

致命错误:未捕获错误:在null上调用成员函数select()

PHP PDO:致命错误:未捕获的错误:在第[duplicate]行上对bool成员函数execute()的调用