Skip to content

Instantly share code, notes, and snippets.

@mallardduck
Created March 20, 2022 19:48
Show Gist options
  • Save mallardduck/d54597ecb9359b86a80d8d7eb66a5611 to your computer and use it in GitHub Desktop.
Save mallardduck/d54597ecb9359b86a80d8d7eb66a5611 to your computer and use it in GitHub Desktop.
Laravel Human date time diff example
<x-human-date-time-diff :date-time="$post->posted_at"></x-human-date-time-diff>
<time datetime="{{ $dateTime->toW3cString() }}" title="{{ $dateTime->format('Y-m-d \a\t H:i A O') }}">{{ $dateTime->diffForHumans() }}</time>
<?php
namespace App\View\Components;
use Carbon\Carbon;
use Illuminate\View\Component;
class HumanDateTimeDiff extends Component
{
public $dateTime;
/**
* Create a new component instance.
*
* @param Carbon $dateTime
*/
public function __construct(Carbon $dateTime)
{
$this->dateTime = $dateTime;
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
*/
public function render(): \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
{
return view('components.human-date-time-diff');
}
}
@caendesilva
Copy link

caendesilva commented Mar 20, 2022

Awesome! I recall doing something similar too. I love the Time element and usually also use a human readable time as a title.

To make it even shorter just using <x-human-date-time-diff :date-time="$post->posted_at" /> is enough!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment