Home > front end >  PHP Fatal error: Uncaught Error: Call to a member function diff() on string in
PHP Fatal error: Uncaught Error: Call to a member function diff() on string in

Time:12-18

I have order date time stored in mysql database. I am getting it. Now I am converting it to users local timezone and then adding 1 day in it.

Now What I am looking to do is getting how many hours and minutes remain in above date time in compare of current localtime of user. My code is like below

$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;

But its giving me error called

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

I am not getting idea how to solve the issue, Let me know if anyone here can help me for do the same.

Thanks!

CodePudding user response:

The Fatal error raises in this line:

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

It means that you try to call diff method of object, but $order_expiry_date has type of string.

Add debug statement before the line to ensure:

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

It should output something like string(19) "2021-06-26 15:55:32".

To fix the error, you should do some steps:

  1. Convert $order_expiry_date from string to DateTime object.
  2. Replace $now argument (its type is also string) with Datetime object

Result is below:

<?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.

  • Related