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

Date Format Converter Laravel Package

danharrin/date-format-converter

Convert date/time format strings between PHP, Moment.js, ICU and more. Handy for Laravel apps that need consistent formatting across backend and frontend, with simple helpers to translate patterns and reduce duplicated format definitions.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require danharrin/date-format-converter
    

    No configuration is required—just autoload the package.

  2. First Use Case: Convert a Date String

    use DanHarrin\DateFormatConverter\Converter;
    
    $converter = new Converter();
    $converted = $converter->convert('2024-06-13', 'Y-m-d', 'd/m/Y');
    // Output: "13/06/2024"
    
  3. Where to Look First

    • Converter class: Core functionality for format conversions.
    • Converter::convert(): Primary method for token-based conversions.
    • Converter::getFormat(): Extract tokens from a format string (e.g., 'Y-m-d'['Y', 'm', 'd']).
    • Converter::getDate(): Parse a date string into a DateTime object.

Implementation Patterns

Common Workflows

  1. Dynamic Format Handling Useful for user-submitted formats (e.g., CMS or API inputs):

    $userFormat = request('date_format'); // e.g., "MM/DD/YYYY"
    $converter->convert($dateString, 'Y-m-d', $userFormat);
    
  2. Batch Processing Convert arrays of dates efficiently:

    $dates = ['2024-01-01', '2024-02-01'];
    $formatted = array_map(
        fn($date) => $converter->convert($date, 'Y-m-d', 'Y.m.d'),
        $dates
    );
    // Output: ["2024.01.01", "2024.02.01"]
    
  3. Integration with Laravel

    • Form Requests: Validate and sanitize date formats:
      public function rules()
      {
          return ['date' => 'required|date_format:Y-m-d'];
      }
      
    • Carbon Compatibility: Convert to/from Carbon:
      $carbon = Carbon::parse('2024-06-13');
      $converted = $converter->convert($carbon->format('Y-m-d'), 'Y-m-d', 'd/m/Y');
      
  4. Localization Handle locale-specific formats (e.g., German d.m.Y):

    $converter->convert('2024-06-13', 'Y-m-d', 'd.m.Y'); // "13.06.2024"
    

Advanced Patterns

  1. Custom Token Support Extend the converter for non-standard tokens (e.g., Q for quarter):

    $converter->addToken('Q', fn(DateTime $date) => $date->format('Q'));
    $converter->convert('2024-06-13', 'Y-m-d', 'Y-Q'); // "2024-2"
    
  2. Fallback Formats Handle ambiguous inputs gracefully:

    try {
        $converted = $converter->convert('06/13/2024', 'm/d/Y', 'd/m/Y');
    } catch (InvalidArgumentException $e) {
        // Fallback to default parsing
    }
    
  3. Testing Mock the Converter in unit tests:

    $converter = $this->createMock(Converter::class);
    $converter->method('convert')
        ->with('2024-06-13', 'Y-m-d', 'd/m/Y')
        ->willReturn('13/06/2024');
    

Gotchas and Tips

Pitfalls

  1. Token Mismatches

    • Issue: convert('2024-06-13', 'Y-m-d', 'd-m-Y') may fail if the input doesn’t match the source format.
    • Fix: Always validate input formats or use getDate() first:
      $date = $converter->getDate('2024-06-13', 'Y-m-d');
      $converted = $date->format('d-m-Y');
      
  2. Timezone Sensitivity

    • Issue: DateTime objects respect the system timezone. Use setTimezone() if needed:
      $date = $converter->getDate('2024-06-13', 'Y-m-d');
      $date->setTimezone(new DateTimeZone('UTC'));
      
  3. Locale-Specific Parsing

    • Issue: Some formats (e.g., d/m/Y) may parse incorrectly in non-English locales.
    • Fix: Explicitly set the locale for DateTime:
      $date = DateTime::createFromFormat('d/m/Y', '13/06/2024', new DateTimeZone('en_GB'));
      
  4. Edge Cases in Tokens

    • Issue: Custom tokens may not handle DateTime edge cases (e.g., invalid dates).
    • Fix: Wrap custom logic in try-catch:
      $converter->addToken('week', fn(DateTime $date) => {
          try {
              return $date->format('W');
          } catch (Exception $e) {
              return '0';
          }
      });
      

Debugging Tips

  1. Inspect Tokens Use getFormat() to debug token extraction:

    print_r($converter->getFormat('Y-m-d H:i:s')); // ['Y', 'm', 'd', 'H', 'i', 's']
    
  2. Log Conversions Add logging for troubleshooting:

    $converter->convert('2024-06-13', 'Y-m-d', 'd/m/Y', true); // Enable debug mode
    
  3. Fallback to Carbon For complex cases, leverage Carbon’s parsing:

    $date = Carbon::createFromFormat('Y-m-d', '2024-06-13');
    $converted = $date->format('d/m/Y');
    

Extension Points

  1. Custom Token Registry Override the default tokens by extending the Converter class:

    class CustomConverter extends Converter {
        public function __construct() {
            $this->addToken('custom', fn(DateTime $date) => 'CUSTOM');
        }
    }
    
  2. Integration with Laravel Helpers Create a global helper:

    if (!function_exists('convert_date')) {
        function convert_date(string $date, string $from, string $to): string {
            return app(Converter::class)->convert($date, $from, $to);
        }
    }
    

    Usage:

    convert_date('2024-06-13', 'Y-m-d', 'd/m/Y');
    
  3. Service Provider Binding Bind the converter to Laravel’s container for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->bind(Converter::class, fn() => new Converter());
    }
    

    Usage in controllers:

    public function __construct(private Converter $converter) {}
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport