Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Human Date Laravel Package

cocur/human-date

Transforms DateTime values into human‑readable strings like Today, Tomorrow, Yesterday, Next Tuesday, or formatted dates. Supports translated strings via a translation interface (including Symfony Translation). Lightweight, no external dependencies, PSR‑4, PHP 5.4+ and HHVM.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cocur/human-date
    

    No additional autoload configuration is required for Laravel 5.5+ (PSR-4 compliant).

  2. First Use Case: Convert a Carbon instance to a human-readable string:

    use Cocur\HumanDate\HumanDate;
    use Carbon\Carbon;
    
    $date = Carbon::now();
    $humanDate = new HumanDate($date);
    echo $humanDate->get(); // Outputs: "a few seconds ago" or "just now"
    
  3. Where to Look First:

    • GitHub Repository (if available).
    • Focus on the HumanDate class methods: get(), getRelative(), and getAbsolute().
    • Check the class for default configurations (e.g., language, precision).

Implementation Patterns

Core Workflows

  1. Basic Date Formatting:

    $humanDate = new HumanDate($carbonDate);
    echo $humanDate->get(); // "2 hours ago"
    
  2. Relative vs. Absolute:

    • Use getRelative() for time-ago strings (e.g., "yesterday").
    • Use getAbsolute() for formatted dates (e.g., "Jan 1, 2023").
    echo $humanDate->getRelative(); // "last week"
    echo $humanDate->getAbsolute(); // "Jan 1, 2023"
    
  3. Customizing Output: Override defaults via constructor:

    $humanDate = new HumanDate($carbonDate, [
        'precision' => 2, // Show "2 hours ago" instead of "2 hours and 30 minutes ago"
        'language' => 'fr', // French translations (if supported)
    ]);
    
  4. Integration with Laravel:

    • Service Provider: Bind HumanDate to the container for easy dependency injection:
      $this->app->bind(HumanDate::class, function ($app) {
          return new HumanDate($app->make(Carbon::class));
      });
      
    • Helper Function: Add to AppServiceProvider's boot():
      if (!function_exists('human_date')) {
          function human_date($date = null, array $options = [])
          {
              $carbonDate = $date ?? now();
              return (new \Cocur\HumanDate\HumanDate($carbonDate, $options))->get();
          }
      }
      
      Usage:
      echo human_date($post->created_at); // "3 days ago"
      
  5. Dynamic Date Handling: Useful in views or controllers for timestamps:

    // In a Blade view:
    <p>Posted {{ human_date($post->created_at) }}</p>
    

Gotchas and Tips

Pitfalls

  1. Initial Release Limitations:

    • v0.1 is a port from BraincraftedHumanDateBundle and may lack some features or stability.
    • Tip: Test thoroughly with your stack (PHP 8.x, Laravel 9.x, Carbon 2.x).
  2. Language Support:

    • Defaults to English. Limited language support in the initial release.
    • Tip: Extend the package by adding custom translations via the constructor or a wrapper class.
  3. Precision Quirks:

    • precision option may not behave as expected for edge cases (e.g., dates exactly 1 minute apart).
    • Debugging: Log the raw output of getRelative() or getAbsolute() to inspect formatting.
  4. Time Zone Sensitivity:

    • Relies on Carbon’s time zone. Ensure your Carbon instance uses the correct time zone:
      $date->setTimezone('America/New_York');
      
  5. Caching Static Outputs:

    • If using in loops (e.g., listing posts), cache the HumanDate instance to avoid redundant calculations:
      $posts->each(function ($post) {
          $post->humanReadableDate = cache()->remember(
              "human_date_{$post->id}",
              now()->addHours(1),
              fn() => human_date($post->created_at)
          );
      });
      

Debugging Tips

  1. Inspect Raw Methods: Call getRelative() and getAbsolute() separately to isolate issues:

    var_dump($humanDate->getRelative(), $humanDate->getAbsolute());
    
  2. Check Carbon Input: Verify the Carbon instance’s values before passing to HumanDate:

    dd($carbonDate->toDateTimeString());
    
  3. Override Defaults: If translations or formatting are off, subclass HumanDate:

    class CustomHumanDate extends \Cocur\HumanDate\HumanDate
    {
        public function __construct(\DateTimeInterface $date)
        {
            parent::__construct($date, [
                'language' => 'custom',
                'translations' => [
                    'just now' => 'justo ahora',
                    // ...
                ],
            ]);
        }
    }
    

Extension Points

  1. Add Custom Rules: Extend the logic by subclassing and overriding methods like _getRelativeTimeString() or _getAbsoluteTimeString().

  2. Plugin System: Create a trait or decorator to add pre/post-processing:

    trait HumanDateEnhancer
    {
        public function getEnhanced()
        {
            $relative = $this->getRelative();
            return str_replace('ago', 'since', $relative); // Example modification
        }
    }
    
  3. Database Storage: Store human-readable dates in the DB for non-technical users, but ensure they’re regenerated on read:

    // Migration:
    $table->text('human_readable_date')->nullable();
    
    // Model:
    public function getHumanReadableDateAttribute()
    {
        return human_date($this->created_at);
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui