1

In my Laravel-8, I have this in my view blade:

{{$duration['time_spent'] ?? '' }}

time_spent is in seconds. How do I convert it to hours in human readable

For instance, 4 Hours 20 Minutes

time_spent is something like: 124323.4

When I did

{{$duration['time_spent']->diffForHumans() ?? '' }}

I got this error:

Call to a member function diffForHumans() on float

How do I resolve it?

Thanks

user11352561
  • 2,277
  • 12
  • 51
  • 102

3 Answers3

5

Usually you can use Carbon for all actions with date in laravel (https://carbon.nesbot.com/)

For your task:

CarbonInterval::seconds($duration['time_spent'])->cascade()->forHumans();

UPD: blade file

\Carbon\CarbonInterval::seconds($duration['time_spent'])->cascade()->forHumans();
V-K
  • 1,297
  • 10
  • 28
  • @OMR `22:10` is not a valid value for `::seconds()`... Where are you getting that value from this question? `124323.4` is the number of seconds in the question. – Tim Lewis Mar 30 '21 at 14:15
  • @V-K - I'm converting it to hours. From what you gave, I got the error: [previous exception] [object] (Error(code: 0): Class 'CarbonInterval' not found – user11352561 Mar 30 '21 at 14:15
  • now I got it, very cool ! thank @TimLewis – OMR Mar 30 '21 at 14:37
  • This piece of code has a problem in too many seconds https://stackoverflow.com/questions/72445614/how-to-convert-time-in-seconds-to-human-readable – omid May 31 '22 at 09:49
0

You can try this

{{gmdate("H:i:s", $duration['time_spent'])?? ''}};
Basharmal
  • 1,313
  • 10
  • 30
0

I'm sure Carbon has a dedicated method for this operation, but just for fun, I tried to create a function to do the job.

I tested my code with small and large numbers. I know it works with small ones, and it seems OK with large numbers, but I didn't verify.

public function convertTime($sec)
{
    $timeParts = [];
    foreach ($this->durations() as $tf => $duration) {
        extract($this->createTimeString($sec, $tf, $duration));
        array_push($timeParts, $timeString);
    }
    return implode(' ', array_filter($timeParts, function ($item) {
        return $item != '';
    }));
}

private function durations()
{
    return array_reverse([
        'second' => 1,
        'minute' => $minute = 60,
        'hour' => $hour = $minute * 60,
        'day' => $day = $hour * 24,
        'week' => $day * 7,
        'month' => $day * 30,
        'year' => $day * 365
     ]);
}

private function createTimeString($sec, $tf, $duration)
{
    $howManyLeft = floor($sec / $duration);
    return [
        'sec' => !$howManyLeft ? $sec : $sec - $howManyLeft * $duration,
        'timeString' => !$howManyLeft ? '' : $howManyLeft . " $tf" . ($howManyLeft > 1 ? 's' : '')
    ];
}

// convertTime(3684615) returns 1 month 1 week 5 days 15 hours 30 minutes 15 seconds
Bulent
  • 3,307
  • 1
  • 14
  • 22