wip: a macro to extend Carbon\Carbon with a nice interval

This commit is contained in:
Brian 2022-05-20 13:52:42 -06:00
parent 78bb0f72d5
commit 2d9eb8640b
Signed by: brian
GPG Key ID: DE1A5390A3B84CD8
2 changed files with 98 additions and 0 deletions

View File

@ -0,0 +1,76 @@
<?php
namespace App\Providers;
use Carbon\Carbon;
use Illuminate\Support\ServiceProvider;
class CarbonServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
Carbon::macro('getHumanInterval', function ($other) {
$isNow = $other === null;
if ($isNow) {
$other = static::now($this->tz);
}
$diffInMinutes = $this->diffInMinutes($other);
$minutes = $diffInMinutes % 60;
$diffInHours = $diffInMinutes / 60;
$hours = $diffInHours % 60;
$diffInDays = $diffInHours / 24;
$days = $diffInDays % 24;
$diffInWeeks = $diffInDays / 24;
$weeks = $diffInWeeks % 24;
$diffInMonths = $diffInWeeks / 7;
$months = $diffInMonths % 7;
$diffInYears = $diffInMonths / 12;
$years = $diffInYears % 12;
$outputArray = [];
if ($years > 0) {
$outputArray['years'] = "$years years";
}
if ($months > 0) {
$outputArray['months'] = "$months months";
}
if ($weeks > 0 && $days === 0) {
$outputArray['weeks'] = "$weeks weeks";
}
if ($days > 0) {
$outputArray['days'] = "$days days";
}
if ($hours > 0) {
$outputArray['hours'] = "$hours hours";
}
if ($minutes > 0) {
$outputArray['minutes'] = "$minutes minutes";
}
return implode(', ', $outputArray);
});
}
}

22
src/config/app.php Normal file
View File

@ -0,0 +1,22 @@
<?php
...
return [
...
'providers' => [
...
/*
* Application Service Providers...
*/
...
App\Providers\CarbonServiceProvider::class,
],
...
];