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

Timezone Laravel Package

adlawson/timezone

Sets PHP’s default timezone to UTC when date.timezone isn’t configured, preventing DateTime “not safe to rely on system timezone” warnings. Auto-runs on include (side effect), intended for end-user apps/frameworks, not libraries.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require adlawson/timezone:1.0.0
    

    Add the autoloader to your entry point (e.g., index.php or bootstrap/app.php):

    require __DIR__.'/vendor/autoload.php';
    
  2. First Use Case:

    • If your Laravel app triggers the DateTime timezone warning (e.g., during php artisan serve or API requests), this package silently enforces UTC as the default timezone, eliminating the warning.
    • Test by running:
      php artisan tinker
      >>> new DateTime(); // No warning, defaults to UTC
      

Where to Look First

  • Source Code: lib/timezone.php (single file, ~50 lines).
  • Laravel Integration: No config needed—just autoload. For debugging, check if date_default_timezone_get() returns UTC after autoloading.

Implementation Patterns

Usage Patterns

  1. Framework-Agnostic Initialization:

    • Place require __DIR__.'/vendor/autoload.php'; before any DateTime usage in your Laravel app’s entry point (e.g., public/index.php or bootstrap/app.php).
    • Example for Laravel’s bootstrap/app.php:
      require __DIR__.'/../vendor/autoload.php'; // <-- Add this line early
      $app = new Application();
      
  2. Testing Timezone Behavior:

    • Use date_default_timezone_get() in tests to verify UTC is enforced:
      use function PHPUnit\Framework\assertEquals;
      
      public function testTimezoneIsUTC()
      {
          assertEquals('UTC', date_default_timezone_get());
      }
      
  3. Avoiding Side Effects:

    • Since the package violates PSR-1, do not use it in libraries/plugins. Reserve it for end-user applications (e.g., Laravel apps).

Workflows

  1. Debugging Timezone Warnings:

    • If warnings persist after autoloading, check:
      • php.ini for date.timezone overrides.
      • Server environment (e.g., shared hosting may restrict date_default_timezone_set()).
    • Use error_reporting(E_ALL) to confirm the warning is suppressed.
  2. Laravel-Specific Integration:

    • Combine with Laravel’s config/app.php timezone setting (if present) by placing the autoloader before Laravel boots:
      // bootstrap/app.php
      require __DIR__.'/../vendor/autoload.php'; // Force UTC first
      $app = new Application();
      
  3. Fallback for Dynamic Environments:

    • Useful in CI/CD pipelines or Docker containers where php.ini isn’t configurable:
      # docker-compose.yml
      services:
        app:
          image: php:8.2-cli
          volumes:
            - ./vendor:/var/www/vendor
          command: php -d date.timezone=UTC script.php  # Redundant but explicit
      

Integration Tips

  • Composer Scripts: Add to composer.json to auto-enforce UTC during testing:
    "scripts": {
      "test": "php -d date.timezone=UTC vendor/bin/phpunit",
      "pre-autoload-dump": "php -d date.timezone=UTC vendor/bin/composer dump-autoload"
    }
    
  • Laravel Service Providers: If you must initialize after Laravel boots, use a service provider’s boot() method:
    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    
    class TimezoneProvider extends ServiceProvider
    {
        public function boot()
        {
            if (date_default_timezone_get() === false) {
                date_default_timezone_set('UTC');
            }
        }
    }
    
    (Note: This is redundant if the package is already loaded, but useful for explicit control.)

Gotchas and Tips

Pitfalls

  1. PSR-1 Violation:

    • The package executes code on autoload, which violates PSR-1 §2.3. This can cause:
      • Unexpected behavior in libraries that assume date.timezone is untouched.
      • Issues with static analysis tools (e.g., PHPStan) flagging side effects.
    • Workaround: Only use in application code, not libraries.
  2. Redundant Overrides:

    • If date.timezone is already set in php.ini or via ini_set(), the package’s check may still run but won’t override. Test with:
      php -d date.timezone=America/New_York -r "require 'vendor/autoload.php'; echo date_default_timezone_get();"
      
      (Should output UTC, not America/New_York.)
  3. Laravel Caching:

    • If using Laravel’s OPcache or config_cache, the autoloader may run once during boot. For dynamic environments, ensure the package is loaded before Laravel caches configurations.
  4. Timezone Database Updates:

    • The package uses PHP’s built-in timezone database. If your app relies on IANA timezone updates, ensure your PHP version is up-to-date (e.g., PHP 8.2+ includes newer IANA data).

Debugging

  1. Verify Execution:

    • Check if the package ran by inspecting date_default_timezone_get() in a Laravel Tinker session:
      >>> date_default_timezone_get();
      "UTC"
      
    • If not UTC, the autoloader may not have executed (e.g., cached OPcode).
  2. Suppress Warnings:

    • If warnings persist, explicitly set the timezone in bootstrap/app.php after autoloading:
      require __DIR__.'/../vendor/autoload.php';
      date_default_timezone_set('UTC'); // Explicit fallback
      
  3. Check for Conflicts:

    • Other packages (e.g., vlucas/phpdotenv) might also set timezones. Use strace or xdebug to trace execution order:
      strace -e trace=file php artisan tinker 2>&1 | grep timezone
      

Tips

  1. Explicit Overrides:

    • For production, set date.timezone in php.ini or .env (Laravel) to avoid relying on the package:
      ; php.ini
      date.timezone = UTC
      
      or
      # .env
      APP_TIMEZONE=UTC
      
  2. Testing Edge Cases:

    • Test with date.timezone unset in php.ini:
      php -n -r "require 'vendor/autoload.php'; echo date_default_timezone_get();"
      
      (Should output UTC.)
  3. Alternative for Libraries:

    • If you’re building a library and need timezone safety, require users to set date.timezone in their composer.json or documentation:
      "config": {
        "preferred-install": "dist",
        "timezone": "UTC" // Hint for users
      }
      
  4. Performance Note:

    • The package adds negligible overhead (~1ms on autoload). For micro-optimizations, consider inlining its logic:
      // bootstrap/app.php
      if (function_exists('date_default_timezone_get') && !date_default_timezone_get()) {
          date_default_timezone_set('UTC');
      }
      
  5. Forking for Custom Logic:

    • Fork the package to add logging or custom timezone logic (e.g., detect user’s timezone via IP):
      // Custom timezone.php
      require '/path/to/adlawson/timezone/lib/timezone.php';
      if (date_default_timezone_get() === 'UTC') {
          error_log('UTC enforced by timezone package');
      }
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor