我將訂單日期時間存盤在 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
我不知道如何解決這個問題,讓我知道這里是否有人可以幫助我做同樣的事情。
謝謝!
uj5u.com熱心網友回復:
在這一行中引發了致命錯誤:
<?php
$interval = $order_expiry_date->diff($now);
這意味著您嘗試呼叫 的diff方法object,但$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物件。$now用 Datetime 物件替換引數(它的型別也是字串)
結果如下:
<?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;
PHP 沙箱上的現場演示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/384909.html
