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 Time Laravel Package

php-standard-library/date-time

Immutable, timezone-aware DateTime types for PHP. Provides Duration, Period, and Interval helpers for safer date/time arithmetic and ranges, designed as a standard-library style package with clear docs and contribution links.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require php-standard-library/date-time
    

    Add to composer.json under require or require-dev if needed.

  2. First Use Case: Creating a Timezone-Aware DateTime

    use PhpStandardLibrary\DateTime\DateTime;
    
    $now = DateTime::now('America/New_York');
    echo $now->format('Y-m-d H:i:sP'); // Outputs: 2026-03-20 14:30:45-04:00
    
  3. Key Classes to Explore

    • DateTime (immutable, timezone-aware)
    • Duration (e.g., Duration::fromHours(2.5))
    • Period (e.g., Period::fromDays(7))
    • Interval (e.g., Interval::fromStartEnd($start, $end))
  4. Where to Look First

    • Source Code (if available)
    • tests/ directory for usage examples
    • README.md for basic API docs (if provided)

Implementation Patterns

Core Workflows

1. Timezone-Aware Operations

$nyTime = DateTime::now('America/New_York');
$londonTime = $nyTime->inTimezone('Europe/London');
$diff = $nyTime->diff($londonTime); // Duration object

2. Immutable Manipulation

$tomorrow = $now->add(Duration::fromDays(1));
$yesterday = $now->subtract(Period::fromDays(1));

3. Interval Calculations

$start = DateTime::fromFormat('Y-m-d', '2026-01-01');
$end = DateTime::fromFormat('Y-m-d', '2026-01-31');
$interval = Interval::fromStartEnd($start, $end);
$daysInInterval = $interval->days(); // 31

4. Duration Arithmetic

$meetingDuration = Duration::fromHours(1.5);
$endTime = $now->add($meetingDuration);

5. Periodic Tasks

$weeklyReport = Period::fromWeeks(1);
$nextRun = $now->add($weeklyReport);

Integration Tips

  • Laravel Carbon Compatibility Convert between DateTime and Carbon for existing apps:

    $carbon = Carbon::instance($dateTime);
    $dateTime = DateTime::fromCarbon($carbon);
    
  • Validation Use with Laravel’s Validator for strict date/time checks:

    $validator->rule('due_date', function ($attribute, $value, $fail) {
        $date = DateTime::fromFormat('Y-m-d', $value);
        if ($date->isBefore($now)) {
            $fail('Date must be in the future.');
        }
    });
    
  • API Responses Serialize DateTime objects to ISO 8601 strings:

    return response()->json(['scheduled_at' => $dateTime->toAtomString()]);
    
  • Database Storage Store as UTC in the database, convert on retrieval:

    $utcTime = $dateTime->inTimezone('UTC');
    $storedAt = $utcTime->format('Y-m-d H:i:s');
    

Gotchas and Tips

Pitfalls

  1. Immutability

    • All operations return new instances. Avoid chaining without assignment:
      // ❌ Loses reference
      $now->add(Duration::fromDays(1))->format('Y-m-d');
      
      // ✅ Correct
      $tomorrow = $now->add(Duration::fromDays(1));
      
  2. Timezone Handling

    • Always specify timezones explicitly. Defaults may vary:
      // ❌ Ambiguous
      $dateTime = DateTime::now();
      
      // ✅ Explicit
      $dateTime = DateTime::now('UTC');
      
  3. Duration vs. Period

    • Duration is for time-based intervals (e.g., "2 hours").
    • Period is for calendar-based intervals (e.g., "1 week").
    • Mixing them can lead to unexpected results:
      // ❌ Avoid
      $now->add(Period::fromHours(24)); // Throws exception
      
  4. Leap Seconds

    • The library may not handle leap seconds. Stick to standard timezones.
  5. Legacy Carbon Dependencies

    • If your app relies on Carbon’s createFromFormat, replicate logic:
      // Instead of:
      Carbon::createFromFormat('d/m/Y', '31/12/2025');
      
      // Use:
      DateTime::fromFormat('d/m/Y', '31/12/2025', 'UTC');
      

Debugging Tips

  1. Inspect Timezones

    echo $dateTime->timezone()->getName(); // Debug timezone
    
  2. Format for Clarity

    echo $dateTime->format('Y-m-d H:i:sP e'); // Includes timezone offset and name
    
  3. Compare Objects

    if ($dateTime1->equals($dateTime2)) {
        // ...
    }
    
  4. Use toString() for Debugging

    echo $duration->toString(); // "PT2H30M" for 2.5 hours
    

Extension Points

  1. Custom Formatters Extend the library by creating a formatter trait:

    trait CustomFormatter {
        public function toLaravelFormat(): string {
            return $this->format('Y-m-d H:i:s.u');
        }
    }
    
  2. Add Validation Rules Create a Laravel rule for business logic:

    use PhpStandardLibrary\DateTime\DateTime;
    
    class FutureDateRule extends Rule {
        public function passes($attribute, $value) {
            $date = DateTime::fromFormat('Y-m-d', $value);
            return $date->isAfter(DateTime::now());
        }
    }
    
  3. Event Dispatching Trigger events on date transitions:

    $dateTime->onNextDay(function () {
        event(new DailyTaskScheduled());
    });
    
  4. Database Observers Use with Laravel’s model observers to auto-convert timestamps:

    class DateTimeObserver {
        public function saving(Model $model) {
            if ($model->usesDateTimeAttribute('scheduled_at')) {
                $model->scheduled_at = $model->scheduled_at->inTimezone('UTC');
            }
        }
    }
    
  5. Testing Utilities Create helper methods for tests:

    function createTestDateTime(string $date, string $timezone = 'UTC'): DateTime {
        return DateTime::fromFormat('Y-m-d', $date, $timezone);
    }
    
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