Installation:
composer require alexeyshockov/clock
Add the service provider to config/app.php (if not auto-discovered):
'providers' => [
// ...
Alexeyshockov\Clock\ClockServiceProvider::class,
],
Basic Usage:
Inject the Clock facade or service into your controller/service:
use Alexeyshockov\Clock\Facades\Clock;
// Get current time
$now = Clock::now();
// Format time
$formatted = Clock::now()->format('Y-m-d H:i:s');
First Use Case:
Replace Carbon or DateTime instantiations with Clock::now() for consistency. Example:
// Before
$dueDate = Carbon::now()->addDays(7);
// After
$dueDate = Clock::now()->addDays(7);
Time Zone Handling:
Use Clock::setTimezone('America/New_York') globally or per-operation:
$nyTime = Clock::now('America/New_York');
Mocking Time for Testing: Override time in tests:
Clock::shouldReceive('now')->andReturn(Carbon::create(2023, 1, 1));
Date Arithmetic:
Chain methods like addHours(), subtractMinutes(), or startOfDay():
$nextWeek = Clock::now()->startOfWeek()->addWeek();
Integration with Eloquent:
Use Clock::now() in model timestamps or queries:
$user = User::create([
'name' => 'John',
'created_at' => Clock::now(),
]);
Custom Time Providers: Extend functionality by creating a custom time provider:
Clock::extend('custom', function () {
return new CustomTimeProvider();
});
Archived Package:
nesbot/carbon) are viable.Time Zone Conflicts:
Clock::getTimezone() to debug current timezone.Carbon Dependency:
Clock uses Carbon. Be mindful of Carbon-specific quirks (e.g., createFromFormat edge cases).Service Provider Auto-Discovery:
config/app.php to avoid Clock not being available.Log Current Time:
\Log::debug('Current time:', ['time' => Clock::now()->toDateTimeString()]);
Check Time Providers: List all registered providers to debug overrides:
dd(Clock::providers());
Verify Time Manipulation:
Use toDateTimeString() for debugging formatted output:
$time = Clock::now()->addHours(5);
dd($time->toDateTimeString());
Custom Time Logic:
Override Clock::now() for app-specific logic (e.g., business hours):
Clock::macro('businessHours', function () {
$time = Clock::now();
return $time->hour >= 9 && $time->hour < 17 ? $time : null;
});
Event-Based Time Adjustments: Use Laravel events to dynamically adjust time (e.g., daylight saving):
event(new AdjustTimeEvent());
// In listener:
Clock::setTimezone(request()->ip() ? 'UTC' : 'Europe/London');
Fallback Providers: Implement a fallback provider for offline scenarios:
Clock::extend('offline', function () {
return new StaticTimeProvider(Carbon::now());
});
Clock::setProvider('offline');
How can I help you explore Laravel packages today?