Как получить разницу во времени с помощью Carbon в Laravel - PullRequest
0 голосов
/ 09 января 2020

Я хочу получить разницу во времени между сейчас и subscription_endtime, которые я извлекаю из базы данных. Я использую следующий код

    $subscription_endtime = DB::table('subscriptions')->where('user_id', $user_id)->value('subscription_endtime');
    $today = Carbon::now();
    $totalDuration = $subscription_endtime->diffInSeconds($today);
    return $totalDuration;

Я получаю следующую ошибку

«Вызов функции-члена diffInSeconds () on string».

Как мне решить эту ошибку?

Ответы [ 2 ]

1 голос
/ 09 января 2020
$today = Carbon::now(); //returns todays date and time at this particular second
$from = \Carbon\Carbon::createFromFormat('Y-m-d H:s:i', $subscription_endtime);//returns the time fetched from the database as a Carbon Object

$diff_in_seconds = $today->diffInSeconds($from);//returns the difference between $today and $from in seconds
print_r($diff_in_seconds );//prints the difference
1 голос
/ 09 января 2020

Похоже, subscription_endtime не углеродный объект. Вы можете разобрать его с Carbon

$subscription_endtime = DB::table('subscriptions')->where('user_id', $user_id)->value('subscription_endtime');
$subscription_endtime = Carbon::parse($subscription_endtime); // add this line
$today = Carbon::now();
$totalDuration = $subscription_endtime->diffInSeconds($today);
return $totalDuration;
...