Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Troj's avatar
Level 4

Carbon display hour(s) or minute(s)

I'm trying to display the duration from a timestamp field. I want to display the duration as:

  • 1 hour or
  • 2 hours or
  • 1 minute or
  • 45 minutes

I tried the following, but this returns always 0 hours.

    public function getDisplayHumanDurationAttribute()
    {

        $time = Carbon::createFromFormat('Y-m-d H:i:s', $this->duration);

        return $time->diffInHours($this->duration) . Str::plural(' hour', $time->diffInHours($this->duration));

    }

I'm not even sure if this is the best way to store that duration value in the database. But i thought i could use this in the future when i might have situations where i need to put starts_at and ends_at and then calculate the difference. But for now it's just one timestamp field with the duration in hours or minutes.

0 likes
6 replies
Tray2's avatar

You can use diffForHumans to do that.

$time->diffForHumans()

Example this

$time = Carbon\Carbon::now();

echo $time->diffForHumans();

Would give you something like this

1 second ago
newbie360's avatar

are you looking for

public function getDisplayHumanDurationAttribute()
{
	return Carbon::parse($this->attributes['field_name'])->diffForHumans();
}
Troj's avatar
Level 4

@tray2 and @newbie360 i tried that but that always adds "ago" or something like that at the end. I just need it like 1 hour or 2 hours

Perhaps it's better to just add that duration as a string to the database instead of using a timestamp

newbie360's avatar
Level 24
public function getDisplayHumanDurationAttribute()
{
    return Carbon::parse($this->attributes['field_name'])->diffForHumans(null, true);
}
Tray2's avatar

Then you can do this

$time->diffForHumans(['syntax' => Carbon\CarbonInterface::DIFF_ABSOLUTE]);

it will give you

1 second
Troj's avatar
Level 4

@newbie360 and @tray2 Thanks you both, both answers are doing what i want. But i can only set one as best.

Please or to participate in this conversation.