Search code examples
laravelphp-carbon

How to get difference in time using Carbon in Laravel


I want to get the difference of time between now and subscription_endtime which I am fetching from the database. I am using the following code

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

I am getting the following error

"Call to a member function diffInSeconds() on string".

How do I solve this error?


Solution

  • Looks like subscription_endtime isn't a carbon object. You can parse it from 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;